Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a dictionary contains certain keys

Is there a nice approach to test if a dictionary contains multiple keys?

A short version of:

d = {}
if 'a' in d and 'b' in d and 'c' in d:
    pass #do something

Thanks.

Edit: I can only use python2.4 -.-

like image 479
AkaBkn Avatar asked Aug 05 '10 13:08

AkaBkn


People also ask

How do you check if a dictionary contains a certain key?

Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

How do you check if an item is in a dictionary Python?

Check if Variable is a Dictionary with is Operator We can use the is operator with the result of a type() call with a variable and the dict class. It will output True only if the type() points to the same memory location as the dict class. Otherwise, it will output False .

How do you check if a key is not in a dictionary?

dict provides a function has_key() to check if key exist in dictionary or not.


5 Answers

You can use set.issubset(...), like so:

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> set(['a', 'b']).issubset(d)
True
>>> set(['a', 'x']).issubset(d)
False

Python 3 has introduced a set literal syntax which has been backported to Python 2.7, so these days the above can be written:

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> {'a', 'b'}.issubset(d)
True
>>> {'a', 'x'}.issubset(d)
False
like image 123
Magnus Hoff Avatar answered Nov 15 '22 09:11

Magnus Hoff


if all(test in d for test in ('a','b','c')):
    # do something
like image 44
PaulMcG Avatar answered Nov 15 '22 08:11

PaulMcG


In Python3 you can write

set("abc")<=d.keys()

In Python2.7 you can write

d.viewkeys()>=set("abc")

of course if the keys are not single chars you can replace set("abc") with set(('a', 'b', 'c'))

like image 26
John La Rooy Avatar answered Nov 15 '22 10:11

John La Rooy


Could use an itemgetter wrapped in a try / except.

>>> from operator import itemgetter
>>> d = dict(a=1,b=2,c=3,d=4)
>>> e = dict(a=1,b=2,c=3,e=4)
>>> getter=itemgetter('a','b','c','d')
>>> getter(d)
(1, 2, 3, 4)
>>> getter(e)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'd'

But actually I prefer Paul McGuire's solution

like image 26
MattH Avatar answered Nov 15 '22 08:11

MattH


In 2.4, I always use set operations for such purposes. If it's worth a warning (or other kind of msg or exception) when some expected keys are missing, in particular, I do:

missing = set(d).difference(('a', 'b', 'c'))
if missing:
    logging.warn("Missing keys: %s", ', '.join(sorted(missing)))
else:
    ...

replacing the logging.warn call as appropriate, of course (maybe just logging.info or even logging.debug, maybe logging.error, maybe an exception).

The sorted part is mostly cosmetic (I like reliable, repeatable error messages) but also helps a bit with testing (when I mock up logging.warn -- or whatever -- in the tests, it's nice to be able to expect a specific string, and if I didn't sort the missing set the warning string might vary, of course, since sets, like dicts, don't have a concept of order).

like image 40
Alex Martelli Avatar answered Nov 15 '22 08:11

Alex Martelli