Merge dictionaries without overwriting previous value where value is a list

Viewed 5170

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'.

1 Answers
Related