Merge dictionaries without overwriting previous value where value is a list
dictionary, merge, python
Solution
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)
Problem
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 dictionaries in a single expression?. My problem is slightly different, however. Lets say I have these three dictionaries ``` dict_a = {'a': [3.212], 'b': [0.0]} dict_b = {'a': [923.22, 3.212], 'c': [123.32]} dict_c = {'b': [0.0]} ``` The merged result should be ``` result_dict = {'a': [3.212, 3.212, 923.22], 'b': [0.0, 0.0], 'c': [123.32]} ``` This code here works, but would nest lists within the lists ``` result_dict = {} dicts = [dict_a, dict_b, dict_c] for d in dicts: for k, v in d.iteritems(): result_dict.setdefault(k, []).append(v) ``` Using `extend` instead of `append` would prevent the nested lists, but doesn't work if a key doesn't exist yet. So basically it should do a `update` without the overwriting, as in the other threads. Sorry, it was a mistake on my side. It was too late yesterday and I didn't notice the line that threw the error wasn't the one I thought it did, therefore assumed my dictionaries would already have the above structure. In fact, `mgilson` was correct assuming that it was related to a `TypeError`. To be exact, an 'uniterable float'.