Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using set on Dictionary keys

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.

like image 489
mrQWERTY Avatar asked Jul 04 '26 03:07

mrQWERTY


2 Answers

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
like image 58
mgilson Avatar answered Jul 06 '26 18:07

mgilson


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!