【发布时间】:2016-01-20 16:36:54
【问题描述】:
所以我有 2 个字典列表,如下所示:
list1 = [
{'name':'john',
'gender':'male',
'grade': 'third'
},
{'name':'cathy',
'gender':'female',
'grade':'second'
},
]
list2 = [
{'name':'john',
'physics':95,
'chemistry':89
},
{'name':'cathy',
'physics':78,
'chemistry':69
},
]
我需要的输出列表如下:
final_list = [
{'name':'john',
'gender':'male',
'grade':'third'
'marks': {'physics':95, 'chemistry': 89}
},
{'name':'cathy',
'gender':'female'
'grade':'second'
'marks': {'physics':78, 'chemistry': 69}
},
]
首先我尝试如下迭代:
final_list = []
for item1 in list1:
for item2 in list2:
if item1['name'] == item2['name']:
temp = dict(item_2)
temp.pop('name')
final_result.append(dict(name=item_1['name'], **temp))
但是,这并没有给我想要的结果..我也尝试过 pandas..那里的经验有限..
>>> import pandas as pd
>>> df1 = pd.DataFrame(list1)
>>> df2 = pd.DataFrame(list2)
>>> result = pd.merge(df1, df2, on=['name'])
但是,我不知道如何将数据恢复为我需要的原始格式..任何帮助
【问题讨论】:
-
为什么凯西和凯西在一起?
-
另外,dicts 应该是
[{'physics':78, 'chemistry': 69}],带有大括号。 -
也修复了这个问题..
标签: python list dictionary pandas