Combines two or more dictionaries, creating a list of values for each key.
collections.defaultdict
with list
as the default value for each key and loop over dicts
.dict.append()
to map the values of the dictionary to keys.dict()
to convert the collections.defaultdict
to a regular dictionary.from collections import defaultdict
def combine_values(*dicts):
res = defaultdict(list)
for d in dicts:
for key in d:
res[key].append(d[key])
return dict(res)
d1 = {'a': 1, 'b': 'foo', 'c': 400}
d2 = {'a': 3, 'b': 200, 'd': 400}
combine_values(d1, d2) # {'a': [1, 3], 'b': ['foo', 200], 'c': [400], 'd': [400]}
Python, Dictionary
Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value.
Python, Dictionary
Retrieves the value of the nested key indicated by the given selector list from a dictionary or list.
Python, Dictionary
Creates a flat list of all the keys in a flat dictionary.