简体   繁体   中英

PYTHON: How do i merge two dictionaries inside a list in the most pythonic way

I have a list

result = [
    {
        "name": "James",
        "label":"Student",
        "class": 18
    },
    {
        "name": "Jacob",
        "label":"Professor",
        "class": 18
    },
    {
        "name": "Jeff",
        "label":"Student",
        "class": 19
    }
]

and I want to merge two dictionaries with the same class

I have tried:

res = [{item['label']:item['name'],'class':item['class']} for item in result]

print(res)

>>[{'Student': 'James', 'class': 18}, {'Professor': 'Jacob', 'class': 18}, {'Student': 'Jeff', 'class': 19}] 

sample of desired output:

result = [
    {
        "Student": "James",
        "Professor": "Jacob",
        "class": 18
    },
    {
        "Student": "Jeff",
        "class": 19
    }
]

can someone help me on this one please? Thank you in advance

Define a function called, merge and create a dictionary merged to keep track of visited classes, then whenever a record with the same class in occurred we simply update the dictionary for that class with the key-value pair of label-name :

def merge(dicts):
    merged = {}
    for d in dicts:
        key = d['class']
        if key in merged:
            merged[key][d['label']] = d['name']
        else:
            merged[key] = {'class': d['class'], d['label']: d['name']}
    return list(merged.values())

Result:

# print(merge(result))

[{'Student': 'James', 'class': 18, 'Professor': 'Jacob'}, {'Student': 'Jeff', 'class': 19}]

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