2015-07-10 62 views
0

比方说,我有一个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

下面是使用csvDictReaderdefaultdict的解决方案,这是我在简单的阅读器使用方法:

#!/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())) 

有了:

#!/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 
player_by_position[player["POSITION"]].append(player) 

或者,您精确的输出可以用简单的阅读器实现迭代0


编辑 - 无进口:

#!/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 
+0

能的目标没有进口任何物件可以实现吗? –

+0

@VincentLuc最后见编辑。 –

+0

谢谢,我会看看它。 –