开发者

Some problem in search specific value in specific key

I wants to search specific value in specific key. example:

x = [12, {"hello":"world",}]
if x["hello"] == "world":
   print "Found!"开发者_C百科

My example above is wrong. What to do?


My example above is wrong. What to do?

Correct it, maybe? Honestly, I feel compelled to link to this: How to ask questions the smart way?

That being said, the problem is you are trying to index a list with a string, which is not possible. Either do

x[1]["hello"] == "world"

...or simply get rid of the list, there isn't really a reason to use it, anyway. If you want to store additional data, you might as well use the dictionary for that.


You're mixing dictionaries and lists. You probably don't really know how they work.

Lists may have any object you want and are accessed by their position:

>>> x = ['a', 'b', 'c']
>>> x[2]
'c'

Dicts combine hashable objects (non mutable) as keys with values that can be anything. You access a object by it's key (and they aren't kept ordered).

>>> y = {'a':0, 'b':1, 'c':2}
>>> y['c']
>>> 2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜