5

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.

Saleem Ali
  • 1,363
  • 11
  • 21

2 Answers2

5

Similarly:

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

& means intersection.

sanyassh
  • 8,100
  • 13
  • 36
  • 70
  • It can get even more concise with `print(set() != given_keys & my_dict.keys())` – Michele Bastione Oct 24 '19 at 11:39
  • @MicheleBastione no need to do it. Empty set evaluates to `False` in boolean context. Doing `if some_set:` to check if `some_set` is empty is the most pythonic way. – sanyassh Oct 24 '19 at 12:01
  • Swings and roundabouts I guess. Simply printing the result will try to print the set contents, not true/false. I guess you could bool cast it.. Anyway, in reality I guess you want to do something more interesting with the result than print true/false, so this answer is good for clarifying that. – Gem Taylor Oct 24 '19 at 12:57
0

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()

Franz Kurt
  • 1,020
  • 2
  • 14
  • 14