简体   繁体   中英

Merge values in a list of dictionaries on key

i have that array of dicts:

[{'dog': 'dog-1'}, {'monkey': 'monkey-1'}, {'buffalo': 'buffalo-6'}, {'dog': 'dog-2'},{'pig': 'pig-3'}, {'monkey': 'monkey-6'}, {'monkey': 'monkey-6'}]

And I need to put everyone that has the same key in the same dict. I need that result:

[{'dog': ['dog-1', 'dog-2']}, {'monkey': ['monkey-1', 'monkey-6', 'monkey-6']}, {'buffalo': ['buffalo-6']}, {'pig': ['pig-3']}]

Use a defaultdict :

from collections import defaultdict

lst = [{'dog': 'dog-1'}, {'monkey': 'monkey-1'}, {'buffalo': 'buffalo-6'}, {'dog': 'dog-2'},{'pig': 'pig-3'}, {'monkey': 'monkey-6'}, {'monkey': 'monkey-6'}]

output = defaultdict(list)

for d in lst:
    for k,v in d.items():
        output[k].append(v)

The general idea is, while you're iterating over the list, you want to know if you've reached a dictionary whose key you've already seen before. If you've already seen that key, then you want to append its value to the value of the matching key; if not, you want to create a new key with a default value (in this case an empty list). You can use dict.setdefault to do that.

out = {}
for d in lst:
    for k, v in d.items():
        out.setdefault(k, {}).setdefault(k, []).append(v)
out = list(out.values())

Output:

[{'dog': ['dog-1', 'dog-2']},
 {'monkey': ['monkey-1', 'monkey-6', 'monkey-6']},
 {'buffalo': ['buffalo-6']},
 {'pig': ['pig-3']}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM