Check if any key exist from given multiple keys in a given dictionary

Viewed 136

I know the best way to check if the multiple keys exist in a given dictionary.

if {'foo', 'bar'} <= my_dict.keys():
    # True

Now I have to check if there is any key exist in given dictionary and got so far this:

if any(k in given_keys for k in my_dict):
    # True

I was wondering if there is any way to check this as checked above in first case using subset.

2 Answers

Similarly:

if {'foo', 'bar'} & my_dict.keys():
    print(True)

& means intersection.

Using list compreenssion you can compare two dictionaries:

[x for x in my_dict2 if x in my_dict]

The generator of a dict always use the keys to compare both you will need to use dict.items()

Related