2016-03-17 25 views
1

我的文本文件看起來像這樣:如何將文本放入具有多個值的鍵的字典中?

詹姆斯,10,7,9

利茲,4,6,3

鮑勃,8,2,5

我不得不把它們放到一個字典裏,每個名字都是關鍵字,三個分數都是值。 如何創建只有一個字典並將數據添加到它。 字典應該看起來像:

{ '詹姆斯':[10,7,9], '利茲':[4,6,3], '鮑勃':[8,2,5]}

目前我的代碼看起來是這樣的:

與開放( '類A.TXT')爲f:

lines = f.readlines()[0:4] 

    student1_dict = {} 

    key = None 

    for line in lines: 

     line = line.strip() 

     if not key: 

      key = line 

      student1_dict[key] = [] 

     else: 

      student1_dict[key].append(line) 

打印(student1_dict)

然而,輸出數據以奇怪的格式,因爲它處理的不止是o ne字典。 ?? 這是輸出:

{ '詹姆斯,10,7,9':[ '利茲,4,6,3', '鮑勃,8,2,5', '']}

+0

數字值將在列表中,字典將具有您期望的確切結構。 –

+0

您可以通過在行首添加四個空格來更合適地格式化文件內容和字典。我試圖建議編輯這樣做,但顯然空格不被視爲字符,所以抱怨編輯太短。 (我討厭這些限制。) – glibdud

+0

如何創建字典並同時讀取文件@Walter_Ritzel。我曾多次嘗試同時讀取文件,但它從不將它打印在一本字典中,或者只是崩潰。你可以給任何代碼建議或初學者? – Minions

回答

1

這是獲得你想要的結果的一種方法。這可以使用更緊湊的代碼大大縮短和優化,但這一步更容易解釋。

import csv # import the csv module to help us parse the text file 


# Create an empty dictionary. 
scoreDict = {} 

# Open the text file to parse. 
with open('sample.csv', newline='') as csvfile: 
    # Return an iterable reader object 
    reader = csv.reader(csvfile) 

    # Now we iterate through the reader object. 
    for row in reader: 
     if row: # Ignore empty rows 
      scoresList = [] # Create an empty list we will be adding scores to. 
      # We use the enumerate here to keep track of where we are in the list. 
      for index, column in enumerate(row): 
       if index != 0: # Ignore the first column as we use it as a key      
        # Turn score into an integer and add it to a list. 
        scoresList.append(int(column)) 
        # Add the list of scores to the dictionary. 
        scoreDict[row[0]] = scoresList 

print(scoreDict) 

輸出:

{'Liz': [4, 6, 3], 'Bob': [8, 2, 5], 'James': [10, 7, 9]} 
+0

有沒有使用csv的方法,因爲數據存儲在普通的文本文件中? @Igor – Minions

+0

文件名稱並不重要。它可能也有''sometext.txt''。試試你的文件。 csv模塊在標準庫中,所以使用它不會創建任何依賴關係。如果必須的話,你也可以不用它。 – Igor

+0

我終於明白了csv文件的位。它工作感謝你@Igor – Minions

2

您可以使用字典補償與csv.reader,在Python 3使用extended iterable unpacking創建鍵/值配對:

from csv import reader 

with open("in.csv") as f: 
    dct = {k: list(map(int, rest)) for k,*rest in reader(f, skipinitialspace=1)} 
    print(dct) 

輸出:

{'Bob': [8, 2, 5], 'Liz': [4, 6, 3], 'James': [10, 7, 9]} 

您並不嚴格需要skipinitialspace,因爲int可以處理空格,但如果您希望將值保留爲字符串,您可以添加它或者在數字前面加空格。

如果你使用python2,語法會略有不同,但仍然簡潔明瞭,你只需要切片/指數:

from csv import reader 

with open("in.csv") as f: 
    dct = {row[0]: map(int,row[1:]) for row in reader(f, skipinitialspace=1)} 

如果你只需要添加一個if row空行:

dct = {row[0]: map(int,row[1:]) for row in reader(f, skipinitialspace=1) if row} 

而對於python3:

with open("in.csv") as f: 
    rd = reader(f, skipinitialspace=1) 
    dct = {k: list(map(int, rest)) for k, *rest in filter(None, rd)} 
    print(dct) 

如果你婉噸至使用for循環的邏輯是一樣的,不需要多個循環,索引和切片是Python中非常基本的任務:

from csv import reader 

with open("in.csv") as f: 
    dct = {} 
    for row in reader(f, skipinitialspace=1): 
     # if we have data 
     if row: 
      # index first element to get the key then 
      # slice from the first element to the end casting to int 
      dct[row[0]] = map(int,row[1:]) 
    print(dct) 

的python3代碼可以變成類似以下相同的邏輯的東西。

+0

from csv import reader with open('Class-A.txt')as f:dct = {row [0]:map(int,row [1:])for reader in(f,skipinitialspace = 1)} – Minions

+0

@Walter_Ritzel。這是否是正確的方法?但是它仍然在給出一個錯誤。現在列表索引超出範圍。 ?? – Minions

+0

問題在於文件中有空白行...讓我看看可以做些什麼來解決它。 –

相關問題