2015-01-20 146 views
-1

我無法將多個值分配給字典中的一個鍵。到目前爲止,我已經嘗試了一些方法,而且我最喜歡的一個就是這個。如何將多個值附加到字典中的某個鍵?

from collections import OrderedDict 
from io import StringIO 
f = open('ClassA.txt', 'r') 
dictionary = {} 
for line in f: 
    firstpart, secondpart = line.strip().split(':') 
    dictionary[firstpart.strip()] = secondpart.strip() 
f.close() 
sorted_dict = OrderedDict(sorted(dictionary.items())) 
print(sorted_dict) 
for key, data in dictionary: 
# If this is a new key, create a list to store 
# the values 
    if not key in mydict: 
     dictionary[key] = [] 

基本上ClassA.txt文件包含人的名字和他們的分數,例如:

Dan Scored: 10 
Jake Scored: 9 
Harry Scored: 5 
Berlin Scored: 7 

而我使用的是ordereddic爲了在字母順序鍵(名字)排序。

而我試圖解決的問題是試圖讓相同的用戶aka同名或關鍵能夠存儲multipile分數,所以當他再次測驗時,他的分數將會在他的名字(關鍵字)旁邊。

所以我想實現這個當我打印的詞典:

OrderedDict([('Berlin Scored', '10', '7', '4'), ('Dan Scored', '10'), ('Harry Scored', '5'), ('Jake Scored', '9') 

最好打印多得分從最高到最低的,這將是我的下一個任務,所以我希望得到任何幫助:)

我和我做這件事的道路上遇到的問題是:

for key, data in dictionary: 
ValueError: too many values to unpack (expected 2) 
+1

我會用一個defaultdict和ordereddict – karthikr 2015-01-20 22:29:02

+0

的值,而不是進行排序使用defaultdict,這是很容易排序任何字典輸出。 – 2015-01-20 22:59:37

回答

1

在這裏,你建立你重寫值爲每個關鍵字典時:

for line in f: 
    firstpart, secondpart = line.strip().split(':') 
    dictionary[firstpart.strip()] = secondpart.strip() 

你需要有某種形式的檢查,如:

key = firstpart.strip() 
    val = dictionary.get(key,[]) 
    val.append(secondpart.strip()) 
    dictionary[key] = val 
+0

我在哪裏可以在我的代碼中執行此操作?就像我的名字所說,我在這個全新的可能性世界中開始新鮮。 – 2015-01-20 22:36:02

+0

從字面上替換第一個循環,就像我向你展示的那樣。 – 2015-01-20 22:37:40

+0

獲取屬性錯誤;/val = dictionary.get(key,[])。append(secondpart.strip()) AttributeError:'NoneType'對象沒有屬性'append' – 2015-01-20 22:45:51

相關問題