2015-07-10 61 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

謝謝,我會看看它。 –