For my program, I wish to cleanly check whether any elements in a list is a key in a dictionary. So far, I can only think to loop through the list and checking.
However, is there any way to simplify this process? Is there any way to use sets? Through sets, one can check whether two lists have common elements.
This should be easy using the builtin any function:
any(item in dct for item in lst)
This is quick, efficient and (IMHO) quite readible. What could be better? :-)
Of course, this doesn't tell you which keys are in the dict. If you need that, then you're best recourse is to use dictionary view objects:
# python2.7
dct.viewkeys() & lst # Returns a set of the overlap
# python3.x
dct.keys() & lst # Same as above, but for py3.x
You can test for an intersection between the dictionary's keys and the list items using dict.keys:
if the_dict.keys() & the_list:
# the_dict has one or more keys found in the_list
Demo:
>>> the_dict = {'a':1, 'b':2, 'c':3}
>>> the_list = ['x', 'b', 'y']
>>> if the_dict.keys() & the_list:
... print('found key in the_list')
...
found key in the_list
>>>
Note that in Python 2.x, the method is called dict.viewkeys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With