Python 如何将多个值附加到字典中的键?
我很难将多个值分配到字典中的一个键。到目前为止,我已经尝试了几种方法,其中最接近我的方法就是这个Python 如何将多个值附加到字典中的键?,python,sorting,dictionary,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
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按字母顺序对键(名称)进行排序
我试图解决的问题是,让同一个用户,也就是同一个名字或密钥,能够存储多个文件的分数,这样当他再次进行测验时,他的分数将位于他的名字(密钥)旁边
所以当我打印字典时,我试图做到这一点:
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)
在这里,当您构建字典时,您将覆盖每个键的值:
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
我将使用defaultdict,并对值进行排序,而不是使用OrderedDict使用defaultdict,对输出的任何dict进行排序都非常简单。我可以在代码中的何处实现这一点?正如我的名字所说,我刚开始接触这个充满新可能性的世界。就像我向您展示的那样,替换第一个for循环。获取属性错误;/val=dictionary.get(key,[]).append(secondpart.strip())AttributeError:'NoneType'对象没有属性'append',您可以使用dictionary.setdefault(firstpart.strip(),[]).append(secondpart.strip())Dude,我不会为您调试代码。我已经向您展示了如何替换这一行:
dictionary[firstpart.strip()]=secondpart.strip()