The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Luau

--

Chapters
00:00 Check If Any Of The List Of Keys Are Present In A Dictionary
00:24 Accepted Answer Score 34
00:42 Answer 2 Score 8
01:03 Answer 3 Score 2
01:21 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--