Merge Dictionaries Without Overwriting Previous Value Where Value Is A List
I am aware of Merge dictionaries without overwriting values, merging 'several' python dictionaries, How to merge multiple dicts with same key?, and How to merge two Python dictiona
Solution 1:
I'm pretty sure that .extend
works here ...
>>>dict_a = {'a': [3.212], 'b': [0.0]}>>>dict_b = {'a': [923.22, 3.212], 'c': [123.32]}>>>dict_c = {'b': [0.0]}>>>result_dict = {}>>>dicts = [dict_a, dict_b, dict_c]>>>>>>for d in dicts:...for k, v in d.iteritems():... result_dict.setdefault(k, []).extend(v)...>>>result_dict
{'a': [3.212, 923.22, 3.212], 'c': [123.32], 'b': [0.0, 0.0]}
The magic is in the dict.setdefault
method. If the key doesn't exist, setdefault
adds a new key with the default value you provide. It then returns that default value which can then be modified.
Note that this solution will have a problem if the item v
is not iterable. Perhaps that's what you meant? e.g. if dict_a = {'a': [3.212], 'b': 0.0}
.
In this case, I think you'll need to resort to catching the TypeError: type object is not iterable
in a try-except
clause:
for d in dicts:
for k, v in d.iteritems():
try:
result_dict.setdefault(k, []).extend(v)
except TypeError:
result_dict[k].append(v)
Post a Comment for "Merge Dictionaries Without Overwriting Previous Value Where Value Is A List"