[英]Merging two list of dictionaries based on key
dict1 = [{'id': 1.0, 'name': 'aa'},
{'id': 4.0, 'name': 'bb'},
{'id': 2.0, 'name': 'cc'}]
and和
dict2 = [{'name': 'aa', 'dtype': 'StringType'},
{'name': 'bb', 'dtype': 'StringType'},
{'name': 'xx', 'dtype': 'StringType'},
{'name': 'cc', 'dtype': 'StringType'}]
I would like to merge this two dictionaries based on their common key
which is name
.我想根据它们的公共key
name
合并这两个字典。
I would like to get the following desired result.我想得到以下期望的结果。
merged_dict= [{'id': 1.0, 'name': 'aa', 'dtype': 'StringType'},
{'id': 4.0, 'name': 'bb', 'dtype': 'StringType'},
{'id': 2.0, 'name': 'cc', 'dtype': 'StringType'}]
I was trying to get this using the following for loop.我试图使用以下 for 循环来获取它。
for i in dict1:
for j in dict2:
j.update(i)
To avoid quadratic complexity, better first create a real dictionary (yours are lists of dictionaries), then update
:为了避免二次复杂性,最好先创建一个真正的字典(你的是字典列表),然后update
:
tmp = {d['name']: d for d in dict2}
for d in dict1:
d.update(tmp.get(d['name'], {}))
print(dict1)
Output: Output:
[{'id': 1.0, 'name': 'aa', 'dtype': 'StringType'},
{'id': 4.0, 'name': 'bb', 'dtype': 'StringType'},
{'id': 2.0, 'name': 'cc', 'dtype': 'StringType'}]
Intermediate tmp
:中间tmp
:
{'aa': {'name': 'aa', 'dtype': 'StringType'},
'bb': {'name': 'bb', 'dtype': 'StringType'},
'xx': {'name': 'xx', 'dtype': 'StringType'},
'cc': {'name': 'cc', 'dtype': 'StringType'}}
If you want a copy (rather that modifying dict1
in place):如果你想要一份副本(而不是修改dict1
到位):
tmp = {d['name']: d for d in dict2}
merged_dict = [d|tmp.get(d['name'], {}) for d in dict1]
You can use pandas and try following:您可以使用pandas并尝试以下操作:
import pandas as pd
df1 = pd.DataFrame(dict1)
df2 = pd.DataFrame(dict2)
res = df1.merge(df2, on=['name'])
The output: output:
id name dtype
0 1.0 aa StringType
1 4.0 bb StringType
2 2.0 cc StringType
If you need a dictionary, you can convert merged result pd.DataFrame()
to dict
.如果需要字典,可以将合并结果pd.DataFrame()
转换为dict
。
res.to_dict('records')
Final output is:最后的 output 是:
[
{'id': 1.0, 'name': 'aa', 'dtype': 'StringType'},
{'id': 4.0, 'name': 'bb', 'dtype': 'StringType'},
{'id': 2.0, 'name': 'cc', 'dtype': 'StringType'}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.