简体   繁体   中英

How to merge values of dictionaries with same key into one from a list of dictionaries?

I have a list of dictionaries which looks like below

description = [{"category": "emergency", "meds": [{"drug": "mild", "env": "cold"}]},
               {"category": "normal", "meds": [{"drug": "slow", "env": "normal"}]},
               {"category": "emergency", "meds": [{"drug": "severe", "env": "hot"}]},
               {"category": "medium", "meds": [{"drug": "drowsy", "env": "normal"}]},
               {"category": "normal", "meds": [{"drug": "mild", "env": "normal"}]}]

As you can see for category key, emergency and normal comes twice. Now what I want is to merge the values of those two keys into one such that it looks like below

description_collapsed = [{"category": "emergency", "meds": [{"drug": "mild", "env": "cold"}, {"drug": "severe", "env": "hot"}]},
               {"category": "normal", "meds": [{"drug": "slow", "env": "normal"}, {"drug": "mild", "env": "normal"}]},
               {"category": "medium", "meds": [{"drug": "drowsy", "env": "normal"}]}]

I tried doing something like this

description_collapsed = {}
for i in description:
    if description_collapsed.get(i["category"]):
        description_collapsed.get(i["meds"].extend(i["meds"]))
    else:
        description_collapsed[i["category"]] = i["meds"]

But I only get one dictionary for the meds key of each category.

How can I get the desired output?

i['meds'] is not a key of description_collapses . The rules are the value of description_collapsed.get(i["category"]) , so you need to extend that value.

You also had your parentheses wrong.

Note that your final result will be a dictionary, not a list.

description_collapsed = {}
for i in description:
    if i["category"] in description_collapsed:
        description_collapsed.[i["category"]].extend(i["meds"])
    else:
        description_collapsed[i["category"]] = i["meds"]

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