dictionary - What is the best way to search for a key in multiple dictionaries in Python -
i know can search key in python this:
if key in mydict: #do here
i know can extend , search key in multiple dictionaries using elif statement
if key in mydict_1: #do here elif key in mydict_2: #do here
or doing
if key in (mydict_1.keys() + mydict_2.keys()): #do here
but there more succinct way search key in python in 2 different dicts without using if-else or adding list of keys explicitly ?
the reply question written is:
if any(key in d d in dicts): #
if need know dictionary or dictionaries contain key, can utilize itertools.compress()
:
>>> d1 = dict(zip("kapow", "squee")) >>> d2 = dict(zip("bar", "foo")) >>> d3 = dict(zip("xyz", "abc")) >>> dicts = d1, d2, d3 >>> pprint import pprint >>> pprint(dicts) ({'a': 'q', 'k': 's', 'o': 'e', 'p': 'u', 'w': 'e'}, {'a': 'o', 'b': 'f', 'r': 'o'}, {'x': 'a', 'y': 'b', 'z': 'c'}) >>> itertools import compress >>> d_with_key in compress(dicts, ("a" in d d in dicts)): ... print(d_with_key) ... {'a': 'q', 'p': 'u', 'k': 's', 'w': 'e', 'o': 'e'} {'a': 'o', 'r': 'o', 'b': 'f'}
python dictionary
No comments:
Post a Comment