single key Use in to check if the Key exists in the Dictionary.
Either key in dict.keys () or key in dict can be used as shown below.
In [2]: D = {'abc': 1, 'def': 2, 'ghi': 3, 'jkl' : 4}
In [3]: 'abc' in D.keys()
Out[3]: True
In [4]: 'xyz' in D.keys()
Out[4]: False
In [5]: 'abc' in D
Out[5]: True
By the way, if there is a value, you should use in as well.
In [6]: 1 in D.values()
Out[6]: True
In [7]: 5 in D.values()
Out[7]: False
multiple keys
Use Dictionary view object to check if multiple keys exist. The method of getting the Dictonary view object has changed between python2.7 and python3. Use viewkeys () for python2.7 and keys () for python3.
python2.7
python2.7
In [8]: D.viewkeys() >= {'abc', 'def'}
Out[8]: True
In [9]: D.viewkeys() >= {'abc', 'xyz'}
Out[9]: False
python3 In python3, viewkeys becomes keys.
In [3]: D.keys() >= {'abc', 'def'}
Out[3]: True
In [4]: D.keys() >= {'abc', 'xyz'}
Out[4]: False
To make it work on both, use six and write as follows.
In [6]: import six
In [7]: six.viewkeys(D) >= {'abc', 'def'}
Out[7]: True
In [8]: six.viewkeys(D) >= {'abc', 'xyz'}
Out[8]: False
The method that @shiracamus told me in the comments. In this case, there is no need to import six and it is neat.
In [21]: set(D) >= {'abc', 'def'}
Out[21]: True
In [22]: set(D) >= {'abc', 'xyz'}
Out[22]: False
The method that @shiracamus told me in the comments.
In [2]: all(key in D for key in ('abc', 'def'))
Out[2]: True
In [3]: all(key in D for key in ('abc', 'xyz'))
Out[3]: False
In dictionary view object, you can use & to take intersection. https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects
python2.7
In [14]: len(D.viewkeys() & {'abc', 'xyz'}) > 0
Out[14]: True
In [15]: len(D.viewkeys() & {'x', 'xyz'}) > 0
Out[15]: False
python3
In [10]: len(D.keys() & {'abc','xyz'}) > 0
Out[10]: True
In [11]: len(D.keys() & {'x','xyz'}) > 0
Out[11]: False
The method that @shiracamus told me in the comments.
In [25]: any(key in D for key in ('abc', 'xyz'))
Out[25]: True
In [26]: any(key in D for key in ('abc', 'def'))
Out[26]: True
In [27]: any(key in D for key in ('x', 'xyz'))
Out[27]: False
reference: https://stackoverflow.com/questions/16004593/python-what-is-best-way-to-check-multiple-keys-exists-in-a-dictionary https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects
Recommended Posts