根据共同价值合并2个列表 [英] Merging 2 list of dicts based on common values

查看:114
本文介绍了根据共同价值合并2个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有2个列表,如下所示:

So I have 2 list of dicts which are as follows:

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

我需要的输出列表如下:

The output list i need is as follows:

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))

然而,这并没有给我所需的结果。也尝试过大熊猫有限的经验..

However,this does not give me the desired result..I also tried pandas..limited experience there..

>>> import pandas as pd
>>> df1 = pd.DataFrame(list1)
>>> df2 = pd.DataFrame(list2)
>>> result = pd.merge(df1, df2, on=['name'])

然而,没有任何帮助

推荐答案

您可以首先合并两个数据帧

You can first merge both dataframes

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

然后创建一个标记列作为dict

Then create a marks columns as a dict

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' )选择的数据框列的方法

And, use to_dict(orient='records') method of selected columns of dataframe

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

这篇关于根据共同价值合并2个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆