Python 在词典列表中查找词典编号x
我试图通过使用循环在字典列表中查找特定的字典。但是,我得到一条错误消息:keyrerror:1Python 在词典列表中查找词典编号x,python,list,csv,Python,List,Csv,我试图通过使用循环在字典列表中查找特定的字典。但是,我得到一条错误消息:keyrerror: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]: p
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)
def EU():
错误=0
正确=0
对于欧盟国家:
ans=输入(““+国家[0][1]+”:”的首都是什么)
下大街(ans)
如果ans==国家[1][1]:
打印(“正确”)
正确=正确+1
其他:
打印(“错误。它是:“+country[1][1]”)
错误=错误+1
打印(“正确:+str(正确))
打印(“错误:+str(错误))
打印(“你得到了”+str(正确)+“25分之一”)
#从.csv文件中查找数据
nl={'newline':'''}
模式='r'
如果系统版本信息<(3,0):
nl.pop('newline',无)
模式='rb'
开放式('Europe_Capitals.csv',模式,**nl)为fp:
reader=csv.reader(fp,分隔符=',',引号='')
#下一步(阅读器,无)#跳过标题
dr=[读卡器中的行对行]
欧洲=[]
对于范围(0,51)内的y:
a={
“国家”:dr[y][0],
“资本”:dr[y][1]
},
#印刷品(a)
如果y==51:
a={
“国家”:dr[y][0],
“资本”:dr[y][1]
}
欧洲(a)
该程序旨在循环访问欧洲各国首都并询问我,但我得到的是“国家首都是什么”,现在我只收到一条错误消息,说明KeyError:1
这一部分
a={
“国家”:dr[y][0],
“资本”:dr[y][1]
},#请欢迎使用StackOverflow。请阅读并遵循帮助文档中的发布指南,正如您创建此帐户时所建议的。在此处应用。在您发布MCVE代码并准确指定问题之前,我们无法有效帮助您。我们应该能够将您发布的代码粘贴到文本文件中,然后重新发布减少您指定的问题。您包含了多余的系统代码,并且省略了数据结构。不要读取文件,只需分配目录。我们可以在Europe\u Capitals.csv中查看数据示例吗?如果y==51:
这将永远不会是真的,因为范围(0,51)
停在50
处。既然它与a
的上一个赋值相同,您为什么还要用它呢?