[英]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.