Skip to main content
 首页 » 编程设计

python之根据共同值(value)合并 2 个字典列表

2025年05月04日15wayfarer

所以我有 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']) 

但是,我不知道如何将数据恢复为我需要的原始格式..任何帮助

请您参考如下方法:

您可以先合并两个数据框

In [144]: df = pd.DataFrame(list1).merge(pd.DataFrame(list2)) 

这看起来像,

In [145]: df 
Out[145]: 
   gender   grade   name  chemistry  physics 
0    male   third   john         89       95 
1  female  second  cathy         69       78 

然后创建一个标记列作为字典

In [146]: df['marks'] = df.apply(lambda x: [x[['chemistry', 'physics']].to_dict()], axis=1) 
 
In [147]: df 
Out[147]: 
   gender   grade   name  chemistry  physics  \ 
0    male   third   john         89       95 
1  female  second  cathy         69       78 
 
                                  marks 
0  [{u'chemistry': 89, u'physics': 95}] 
1  [{u'chemistry': 69, u'physics': 78}] 

然后,使用to_dict(orient='records') 数据框选定列的方法

In [148]: df[['name', 'gender', 'grade', 'marks']].to_dict(orient='records') 
Out[148]: 
[{'gender': 'male', 
  'grade': 'third', 
  'marks': [{'chemistry': 89L, 'physics': 95L}], 
  'name': 'john'}, 
 {'gender': 'female', 
  'grade': 'second', 
  'marks': [{'chemistry': 69L, 'physics': 78L}], 
  'name': 'cathy'}]