我在python中有2个dicts列表如下:
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}
},
]
答案 0 :(得分:0)
可能不是最有效的方式,但你有一些提示可以开始。
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))
答案 1 :(得分:0)
您还可以使用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