让我们说下面有一个CSV文件,其中包含一些NFL玩家的数据。我的目标是读取文件,并创建一个以键作为位置的字典,并将值作为元组中播放器配置文件的列表。
(姓名,年龄,身高,体重 - 不包括他们被选中的年份)
我对如何在阅读文件时正确创建字典感到困惑。到目前为止我所处的位置是最底层的,但它很糟糕。
POSITION,NAME,DRAFTED,AGE,HEIGHT,WEIGHT
QB,Aaron,2005,31,6,225
WR,Jordy,2008,30,6,217
WR,Randall,2011,24,5,192
预期字典:
dict = {
QB: [('Aaron', 31, 6, 225)]
WR: [('Jordy', 30, 6, 217), ('Randall', 24, 5, 192)]
}
# Year drafted not included.
矿:
def readTheFile(filename):
read_it = open(filename, 'r')
player_dict = {}
#ignore header row
readFile = read_it.readlines()[1:]
for row in readFile:
k,v = line.split()
d[int(k)] = v
return player_dict
答案 0 :(得分:0)
以下是使用csv
DictReader
和defaultdict
的解决方案,这是我在简单阅读器上使用的方法:
#!/usr/bin/env python
import csv
from collections import defaultdict
with open("players.csv") as f:
reader = csv.DictReader(f)
players = list(reader)
# create position -> player mapping
player_by_position = defaultdict(list)
for player in players:
player_by_position[player["POSITION"]].append(tuple(player.values()))
print player_by_position
它包含了玩家在价值观中的位置,但我希望它足够接近:-)你也可以通过简单地替换来保留玩家的字典来描述它:
player_by_position[player["POSITION"]].append(tuple(player.values()))
使用:
player_by_position[player["POSITION"]].append(player)
或者,您可以使用简单的阅读器通过迭代实现您的确切输出:
#!/usr/bin/env python
import csv
from collections import defaultdict
player_by_position = defaultdict(list)
with open("players.csv") as f:
reader = csv.reader(f)
for row in reader:
player_by_position[row[0]].append(tuple(row[1:])
print player_by_position
修改 - 没有导入:
#!/usr/bin/env python
player_by_position = {}
with open("players.csv") as f:
# skip headers
f.readline()
for line in f:
values = line.strip().split(",")
if not values[0] in player_by_position:
# new position - create new list of players for it
player_by_position[values[0]] = []
player_by_position[values[0]].append(tuple(values[1:]))
print player_by_position