简体   繁体   中英

finding common elements in 2 list of dicts in python

I have 2 list of dicts in python as follows:

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

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

What would be the fastest and most efficient way to combine both these dicts so that the resultant output is as follows:

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

Probably not the most efficient way, but you have some hint to start.

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

You can also use pandas DataFrame : pandas DataFrame

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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