简体   繁体   English

PYTHON:如何以最 Python 的方式将两个字典合并到一个列表中

[英]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我想合并两个具有相同 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:所需 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 :定义一个名为 function 的 function 调用, merge并创建一个merged的字典以跟踪访问的类,然后每当出现具有相同 class 的记录时,我们只需使用label-name的键-值对更新该 class 的字典

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}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 以最pythonic的方式迭代和比较两个python字典以快速执行 - Iterate and compare two python dictionaries in most pythonic way for fast execution 将字典列表合并为一个的更多 Pythonic 方式? - More Pythonic Way to Merge a list of dictionaries into one? Python:合并具有相同键的两个字典的最优雅方式 - Python: Most elegant way to merge two dictionaries with the same key 更新相同字典列表中的字典值的最pythonic方法? - Most pythonic way to update a dictionary value in a list of same dictionaries? 基于另一本字典的 bool 创建字典列表的最 Pythonic 方法 - most pythonic way to create list of dictionaries based on bool of another dictionary 以大多数pythonic方式从词典列表中生成配置样式的文件 - generating config styled file from list of dictionaries in most pythonic way 处理嵌套字典列表的最 Pythonic 方法是什么? - What's the most Pythonic way to deal with a list of nested dictionaries? 如何使用Python以最pythonic的方式转换元组列表(可能使用zip) - How to transform a list of tuples with Python in the most pythonic way (perhaps with zip) 寻找一种更 Pythonic 的方式来将一个充满字典的列表合并成一个? - Looking for a more pythonic way to merge a list full of dictionaries into one? 在Python中合并两个list字典 - To merge two dictionaries of list in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM