【发布时间】:2019-10-18 19:36:25
【问题描述】:
我正在尝试通过使用循环在字典列表中查找特定字典。但是我收到一条错误消息: KeyError: 1
def EU():
wrong = 0
correct = 0
for country in eu:
ans = input("what is the capital of " + country[0][1] + ": ")
str.lower(ans)
if ans == country[1][1]:
print("CORRECT")
correct = correct + 1
else:
print("WRONG. It is: " + country[1][1])
wrong = wrong + 1
print("Correct: " + str(correct))
print("wrong: " + str(wrong))
print("You got " + str(correct) + " out of 25")
#finding the data from a .csv file
nl = {'newline': ''}
mode = 'r'
if sys.version_info < (3, 0):
nl.pop('newline', None)
mode = 'rb'
with open('Europe_Capitals.csv', mode, **nl) as fp:
reader = csv.reader(fp, delimiter=',', quotechar='"')
# next(reader, None) # skip the headers
dr = [row for row in reader]
europe = []
for y in range(0, 51):
a = {
"Country" : dr[y][0],
"Capital" : dr[y][1]
},
#print(a)
if y == 51:
a = {
"Country" : dr[y][0],
"Capital" : dr[y][1]
}
europe.append(a)
该程序旨在循环遍历欧洲的首都并询问我,但我得到的是“国家的首都是什么”,现在我只收到一条错误消息,指出 KeyError: 1
【问题讨论】:
-
欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您指定的问题。你已经包含了多余的系统代码,并省略了你的数据结构。不要读取文件;只需分配您的目录。
-
我们可以看到
Europe_Capitals.csv中的数据样本吗? -
if y == 51:这永远不会是真的,因为range(0, 51)停在50。 -
你为什么还需要那个,因为它和
a之前的分配一样?