Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine dictionaries with the same keys?

I have a list of dictionaries like so:

dicts = [
    {'key_a': valuex1,
     'key_b': valuex2,
     'key_c': valuex3},

    {'key_a': valuey1,
     'key_b': valuey2,
     'key_c': valuey3},

    {'key_a': valuez1,
     'key_b': valuez2,
     'key_c': valuez3}
]

I would like to take these and construct a big dictionary like so:

big_dict = {
    'key_a': [valuex1, valuey1, valuez1],
    'key_b': [valuex2, valuey2, valuez2],
    'key_c': [valuex3, valuey3, valuez3]
}

Is there any elegant "zip"-like way for me to do this?

All the keys are always going to be identical.

like image 851
hide0 Avatar asked Jul 18 '12 01:07

hide0


People also ask

Can you combine dictionaries?

Using the merge operator, we can combine dictionaries in a single line of code. We can also merge the dictionaries in-place by using the update operator (|=).

Can python dictionaries have same keys?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can dictionary have same keys with different values?

You can't. Keys have to be unique.


2 Answers

You can use collections.defaultdict. The benefit of this solution is it does not require keys to be consistent across dictionaries, and it still maintains the minimum O(n) time complexity.

from collections import defaultdict

dict_list = [{'key_a': 'valuex1', 'key_b': 'valuex2', 'key_c': 'valuex3'},
             {'key_a': 'valuey1', 'key_b': 'valuey2', 'key_c': 'valuey3'},
             {'key_a': 'valuez1', 'key_b': 'valuez2', 'key_c': 'valuez3'}]            

d = defaultdict(list)
for myd in dict_list:
    for k, v in myd.items():
        d[k].append(v)

Result:

print(d)

defaultdict(list,
            {'key_a': ['valuex1', 'valuey1', 'valuez1'],
             'key_b': ['valuex2', 'valuey2', 'valuez2'],
             'key_c': ['valuex3', 'valuey3', 'valuez3']})
like image 53
jpp Avatar answered Sep 22 '22 07:09

jpp


big_dict = {}
for k in dicts[0]:
    big_dict[k] = [d[k] for d in dicts]

Or, with a dict comprehension:

{k: [d[k] for d in dicts] for k in dicts[0]}
like image 41
Ned Batchelder Avatar answered Sep 24 '22 07:09

Ned Batchelder