Home > front end >  What is most pythonic way to check if multiple dictionary keys match
What is most pythonic way to check if multiple dictionary keys match

Time:10-19

Suppose I have a dictionary my_dict.

What is the most pythonic way to check if my_dict['a'] == 'b' and my_dict['c'] == 'd' and my_dict['e'] == 'f'?

I do not want it to throw any exception if the keys a, c or e don't exist in my_dict

CodePudding user response:

You can form a tuple with Map and compare it. By Mapping the get method, missing keys will produce a None value and not crash.

(*map(my_dic.get,('a','c','e'),) == ('b','f','d')

CodePudding user response:

You can zip values and keys together and use get() in a generator expression passed to all:

my_dict = {'a':'b', 'c':'d','e':'f'}

keys = ['a', 'c', 'e']
vals = ['b', 'd', 'f']

all(my_dict.get(k) == v for k, v in zip(keys, vals))
# true

This assumes values are not None, since get() returns None for missing values. If that's important, you can check for inclusion as well.

This will be False when keys are missing or values are different like:

my_dict = {'c':'d','e':'f'}

keys = ['a', 'c', 'e']
vals = ['b', 'd', 'f']

all(my_dict.get(k) == v for k, v in zip(keys, vals))
#False

CodePudding user response:

Since this is a very simple use case, where the desired values have near identical character codes to the keys, you can use ord to get the numeric code point or ordinal for a single-character string, and chr to convert it back to a single-character string.

Note that the code point of b is one higher than a, for example.

>>> my_dict = {'a': 'b', 'c': 'd', 'e': 'f'}
>>> keys = ['a', 'c', 'e']
>>> all(my_dict.get(k) == chr(ord(k)   1) for k in keys)
True

A similar approach using map, adapted from the answer above:

>>> list(map(my_dict.get, keys)) == [chr(ord(k)   1) for k in keys]
True

CodePudding user response:

I'll try to provide most understand-friendly and simple code at my opinion:

if my_dict.get('a') == 'b' and my_dict.get('c') == 'd' and my_dict.get('e') == 'f':
  print('all keys exist and values are correct')
else:
  print('one of keys is not exist or value of at least one key is not correct')

my_dict.get(key_name) return None if key_name not exist. b, d and f are not None.

About get method

Also you can catch error:

try:
  if my_dict['a'] == 'b' and my_dict['c'] == 'd' and my_dict['e'] == 'f':
    print('all keys exist and values are correct')
  else:
    print('all keys exist but some of values are not correct')
except KeyError:
  print('some of keys are not exist')

It is so basic but... I guess it is should be here because it basic

  • Related