繁体   English   中英

在python中的2个dicts列表中查找公共元素

[英]finding common elements in 2 list of dicts in python

我在 python 中有 2 个字典列表,如下所示:

profile_list = [
{'name':'suzy',
'gender':'female'
},
{'name':'jim',
'gender':'male'
},
]

marks_list = [
{'name':'suzy',
'physics':95,
'chemistry':89
},
{'name':'jim',
'physics':78,
'chemistry':69
},
]

结合这两个字典的最快和最有效的方法是什么,以便结果输出如下:

final_list = [
{'name':'suzy',
'gender':'female',
'marks': {'physics':95, 'chemistry': 89}
},
{'name':'jim',
'gender':'male'
'marks': {'physics':78, 'chemistry': 69}
},
]

可能不是最有效的方法,但您有一些提示可以开始。

profile_list = [ { 'name':'suzy', 'gender':'female' },
  {'name':'jim', 'gender':'male' }, ]

marks_list = [ {'name':'suzy', 'physics':95, 'chemistry':89 },
{ 'name':'jim', 'physics':78, 'chemistry':69 }, ]

final_list = []

for profile in profile_list:
  for marks in marks_list:
    if profile['name'] == marks['name']:
      a = dict(marks)
      a.pop('name')
      final_list.append(dict(name=profile['name'], **a))

您还可以使用熊猫数据帧:熊猫数据帧

>>> import pandas as pd
>>> df1 = pd.DataFrame(profile_list)
>>> df2 = pd.DataFrame(marks_list)

>>> result = pd.merge(df1, df2, on=['name'])
>>> print result
   gender  name  chemistry  physics
0  female  suzy         89       95
1    male   jim         69       78

[2 rows x 4 columns]

>>> print result.values.tolist()
[['female', 'suzy', 89L, 95L], ['male', 'jim', 69L, 78L]]

>>> result = result.set_index(['name'])

>>> name = raw_input("Enter student name: ")
Enter student name: suzy

>>> sub = raw_input("Enter subject name: ")
Enter subject name: physics

>>> print result[sub][name]
95

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM