简体   繁体   中英

How to convert a Python list of dictionary with same key value into dictionary with list of values

I have a list of dictionary like this:

mylist = [
    {'survival': 124, 'organ': 'Stomach'}
    {'survival': 42, 'organ': 'Stomach'}
    ]

I want to change this into a dictionary with same keys to have list of value like so:

myDict = {
  "survival":[124,42],
  "organ":["Stomach","Stomach"]
}
from collections import defaultdict

mylist = [
    {'survival': 124, 'organ': 'Stomach'},
    {'survival': 42, 'organ': 'Stomach'}
]

mydict_ = defaultdict(list)

for x in mylist:
    for k, v in x.items():
        mydict_[k].append(v)

mydict = dict(mydict_)
print(mydict)

result

{'survival': [124, 42], 'organ': ['Stomach', 'Stomach']}

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