如何将多个值附加到字典中的键?

时间:2015-01-20 22:25:54

标签: python sorting dictionary

我无法将多个值分配到字典中的一个键。到目前为止,我已经尝试了一些方法,最接近我工作的是这个方法。

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以按字母顺序对键(名称)进行排序。

我试图解决的问题是试图让同一个用户名同名或密钥能够存储多重分数,这样当他再次进行测验时,他的分数将在他的名字(关键)旁边。< / p>

所以当我打印字典时,我正试图实现这个目标:

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 个答案:

答案 0 :(得分: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