我有一个csv.DictReader
dicts实例和一个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'}
列表:
[
{'playername': 'Justin Anderson', 'points': '6.94'},
{'playername': 'DeAndre Liggins', 'points': '11.4'},
]
我无法弄清楚如何迭代这些字典列表,匹配Name和playername键,然后从一个字典中吐出['Name']
,从匹配的字典中吐出['points']
。在上面的例子中,我将从两组词中匹配Justin Anderson然后打印出Justin Anderson,6.94
该应用程序的核心需要2个CSV,并使其成为dicts列表。
答案 0 :(得分:1)
这种方式效率不高,但不需要任何预处理:
# 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']])
给出相同的结果。