Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

I have a fixed list of strings. I need to check if any of these strings are a key in the dictionary (just need True or False). I could go

if 'asdf' in dict or 'qwer' in dict or 'zxcv' in dict ... :
    ... do important secret stuff ...

but it seems suboptimal. Is there a more idiomatic way of doing this?

like image 258
Mad Wombat Avatar asked Dec 30 '15 17:12

Mad Wombat


People also ask

How do you check if a dictionary has a list of keys?

Using Keys() The keys() function and the "in" operator can be used to see if a key exists in a dictionary. The keys() method returns a list of keys in the dictionary, and the "if, in" statement checks whether the provided key is in the list. It returns True if the key exists; otherwise, it returns False.

Can keys in a dictionary be duplicated?

First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn't make sense to map a particular key more than once.

How do you check if a key is already present in dictionary?

Check If Key Exists using the Inbuilt method keys() Using the Inbuilt method keys() method returns a list of all the available keys in the dictionary. With the Inbuilt method keys(), use if statement with 'in' operator to check if the key is present in the dictionary or not.


1 Answers

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.

like image 194
Cory Kramer Avatar answered Oct 03 '22 05:10

Cory Kramer