这种方式效率不高,但不需要任何预处理:
# Instead of your CSVReader:
dicts = [{'Salary': '3000', 'Name': 'James Jones', 'GameInfo': 'Den@Cle 07:30PM ET', 'AvgPointsPerGame': '4.883', 'teamAbbrev': 'Cle', 'Position': 'SG'},
{'Salary': '3000', 'Name': 'Justin Anderson', 'GameInfo': 'Orl@Dal 09:00PM ET', 'AvgPointsPerGame': '13.161', 'teamAbbrev': 'Dal', 'Position': 'SF'}]
list_of_dicts = [
{'playername': 'Justin Anderson', 'points': '6.94'},
{'playername': 'DeAndre Liggins', 'points': '11.4'},
]
# For each dictionary in the CSVReader
for dct in dicts:
# For each dictionary in your list of dictionaries
for subdict in list_of_dicts:
# Check if the name and playername matches
if dct['Name'] == subdict['playername']:
# I just print out the results, you need to do your logic here
print(dct['Name'])
print(dct)
print('matching')
print(subdict)
然后打印出来:
Justin Anderson
{'Salary': '3000', 'Name': 'Justin Anderson', 'GameInfo': 'Orl@Dal 09:00PM ET', 'AvgPointsPerGame': '13.161', 'Position': 'SF', 'teamAbbrev': 'Dal'}
matching
{'playername': 'Justin Anderson', 'points': '6.94'}
如果你希望它比你应该预处理你的字典列表更快,这样你就可以简单地查找playername:
>>> dict_of_dicts = {dct['playername']: dct for dct in list_of_dicts}
>>> dict_of_dicts
{'DeAndre Liggins': {'playername': 'DeAndre Liggins', 'points': '11.4'},
'Justin Anderson': {'playername': 'Justin Anderson', 'points': '6.94'}}
然后循环简化为:
for dct in dicts:
if dct['Name'] in dict_of_dicts:
print(dct['Name'])
print(dct)
print('matching')
print(dict_of_dicts[dct['Name']])
给出相同的结果。