I need to check if a particular key is present in some dictionary. I can use has_key ?? Is there any other method to compare the items of the list to the key of dictionary.
I have a list like...[(3,4),(4,5)..] I need to check if the (3,4) 开发者_运维技巧is there in the dictionary.
Something like this?
>>> d = { (1,3):"foo", (2,6):"bar" }
>>> print (1,3) in d
True
>>> print (1,4) in d
False
>>> L = [ (1,3), (1,4), (15) ]
>>> print [ x in d for x in L ]
[True, False, False]
If you want to add missing entries you'll need an explicit loop
for x in L:
if x not in d:
d[x]="something"
The "right" way is using the in
operator like what the other answers have mentioned. This works for anything iterable and you get some speed gains when you can look things up by hashing (like for dictionaries and sets). There's also an older way which works only for dictionaries which is the has_key
method. I don't usually see it around these days and it's slower as well (though not by much).
>>> timeit.timeit('f = {(1,2) : "Foo"}; f.has_key((1,2))')
0.27945899963378906
>>> timeit.timeit('f = {(1,2) : "Foo"}; (1,2) in f')
0.22165989875793457
dictionary.keys()
returns a list of keys
you can then use if (3,4) in d.keys()
精彩评论