简体   繁体   中英

Group list of dict results using python based on first key from each item

I am trying to find the output of this list of dict using Python. Because foo and data are unique keys, the output should merge them.

input = [{'foo': 'foo-main-123'}, {'foo': 'foo-main-345'}, {'data': 'data-main-111'}]
output = {'foo', ['foo-main-123', 'foo-main-345'], 'data': ['data-main-111']}

you can use defaultdict(list) , then iterate each k,v pair in each dict in input.

try this:

from collections import defaultdict

input = [{'foo': 'foo-main-123'}, {'foo': 'foo-main-345'}, {'data': 'data-main-111'}]
output = defaultdict(list)
for d in input:
    for k,v in d.items():
        output[k].append(v)
output=dict(output)
print(output)

Output:

{'foo': ['foo-main-123', 'foo-main-345'], 'data': ['data-main-111']}

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