[英]Why does python “(hash).values()” give an error that "(hash).keys() doesn't give?
I'm a beginner in python. 我是python的初学者。 Still studying basics. 仍在学习基础知识。 I tried below code and it gave me the expected result. 我尝试下面的代码,它给了我预期的结果。
result_f=open("results.txt")
scores={}
for line in result_f:
(name, score)=line.split()
scores[score]=name
result_f.close()
for each in sorted(scores.keys(), reverse=True):
print(each+' '+scores[each])
But if i use 但是如果我用
scores.values()
instead of 代替
scores.keys()
it will give me an error like this 它会给我这样的错误
" Traceback (most recent call last): “追溯(最近一次通话结束):
File "E:\\Practise for MYSELF\\Python\\TEST.py", line 8, in 在第8行的文件“ E:\\ MYSELF \\ Python \\ TEST.py的实践”中
print(each+' '+scores[each]) 打印(每个+''+分数[每个])
KeyError: 'Zack' " KeyError:“ Zack”“
Contents of "result.txt" file are “ result.txt”文件的内容为
Johnny 8.65 约翰尼8.65
Juan 9.12 胡安9.12
Joseph 8.45 约瑟夫8.45
Stacey 7.81 史黛西7.81
Aideen 8.05 艾登8.05
Zack 7.21 扎克7.21
Aaron 8.31 亚伦8.31
please explain me, why does that error occur and how to fix it? 请向我解释,为什么会发生该错误以及如何解决?
Dictionary lookup the value by key, not key by its value. 字典按键查找值,而不按键查找值。 The scores.keys()
return the keys of the dict, while scores.values()
return the values. scores.keys()
返回字典的键,而scores.values()
返回值。 Then scores[key]
is getting the value using the key, so in this case the scores dictionary doesn't have the key Zack
. 然后scores[key]
使用该键获取值,因此在这种情况下,scores字典没有键Zack
。 Instead, Zack
is a value. 相反, Zack
是一个值。
When you switch scores.keys()
to scores.values()
, now the variable each
doesn't store scores (numbers) like it used to. 现在,当将scores.keys()
切换为scores.values()
, each
变量each
不再像以前那样存储分数(数字)。 Instead, it stores names (strings) which can't be used inside the []
operator to look up values in the array. 相反,它存储名称(字符串),这些名称(字符串)不能在[]
运算符内使用以在数组中查找值。
What you probably wanted to do instead is have the loop go through every possible name and find the score associated with it. 您可能想做的是让循环遍历每个可能的名称并找到与之关联的分数。 However, in order to do this you don't change the loop, you change the array. 但是,为了做到这一点,您无需更改循环,而只需更改数组。
To do this, the only line you need to change is scores[score]=name
. 为此,您唯一需要更改的行是scores[score]=name
。 Try changing it to scores[name]=score
. 尝试将其更改为scores[name]=score
。 This will now store the names as keys and the scores as values. 现在,这会将名称存储为键,将分数存储为值。 If you run the code below, you will see that instead of having scores first and then names, you will have names first and then scores like I'm assuming you want. 如果您运行下面的代码,您将看到,比起先得分然后再命名,您将先命名然后再得分,就像我假设的那样。 This matches the format of the input file you posted. 这与您发布的输入文件的格式匹配。
result_f=open("results.txt")
scores={}
for line in result_f:
(name, score)=line.split()
scores[name]=score
result_f.close()
for each in sorted(scores.keys(), reverse=True):
print(each+' '+scores[each])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.