The Python Oracle

Check if any of the list of keys are present in a dictionary

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Darkness Approaches Looping

--

Chapters
00:00 Question
00:32 Accepted answer (Score 31)
00:54 Answer 2 (Score 7)
01:20 Answer 3 (Score 2)
01:46 Thank you

--

Full question
https://stackoverflow.com/questions/3453...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 34


You could use any and iterate over each key you want to check

if any(key in dict for key in ['asdf', 'qwer', 'zxcf']):
    # contains at least one of them

This will short-circuit and return True upon finding the first match, or will return False if it finds none.




ANSWER 2

Score 8


You could also use &:

keys =  ['asdf', 'qwer', 'zxcf']
if d.keys() & keys:
    print(d)

You would need d.viewkeys() for python2.

Alternatively, make keys a set and see if the set is disjoint or not, which will be the fastest approach:

keys =  {'asdf', 'qwer', 'zxcf'}

if not keys.isdisjoint(d):
    print(d)



ANSWER 3

Score 2


you could try using list comprehension in python:

if any([True for entry in your_list if entry in dict]):
    --dostuff--

EDIT: CoryKramer suggested to remove the '[]' in order to make this a generator, rather than evaluate the entire list before checking if any elements are "True":

if any(True for entry in your_list if entry in dict):
    --dostuff--