views:

48

answers:

3

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.

+2  A: 

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"
Michael Anderson
what if, I want to check, if a key is available in the dictinary or not...if not...then add that key to the dic...??
Shilpa
That's a new question, but take a look at the `setdefault()` method. http://docs.python.org/library/stdtypes.html?highlight=setdefault#dict.setdefault
Tim Pietzcker
how about update method.I think, if the key is already there in the dictionary, it will put another value of that key, so we get multiple entries thru update method.
Shilpa
ok..I got the ans...thanks guys
Shilpa
A: 

dictionary.keys() returns a list of keys you can then use if (3,4) in d.keys()

stefano palazzo
No need. The `in` operator when applied to a dictionary will look in the dict's keys.
Tim Pietzcker
A: 

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
Noufal Ibrahim
how to use the In operator?
Shilpa
Check the other answers and my code snippet.
Noufal Ibrahim