我试图让用户进入一个城市,并将温度保存到字典中。但是,Python一直告诉我,我得到了一个KeyError。为什么会发生这种情况?我该如何解决这个问题?谢谢。
def main():
city = {}
keepgoing = True
while keepgoing:
user = input("Enter city followed by temperature: ")
for valu in user.split():
city[valu] = city[valu]+1
if user == "stop":
keepgoing = False
print(city)
main()
答案 0 :(得分:2)
将你的for循环更改为:
city = {}
while keepgoing:
user = input("Enter city followed by temperature: ")
for valu in user.split():
if valu not in city:
city[value] = 0
city[value] = city[value]+1
您收到错误,因为第一次valu
不是city
中的关键字。结果,city[valu]
失败。当密钥不存在时将其设置为0
(或其他一些默认值)将解决您的问题
答案 1 :(得分:1)
要解决当前问题,请替换:
city[valu] = city[valu]+1
使用:
city[valu] = city.get(valu, 0) + 1
city.get(valu)
与city[valu]
类似,只是如果密钥不存在,它会提供默认值None
。 city.get(valu, 0)
类似,但它将默认值设置为0
。
猜测你想要什么,这里是对代码的重写:
def main():
city = {}
while True:
user = input("Enter city followed by temperature: ")
if user == "stop":
print(city)
break
name, temperature = user.split()
city[name] = temperature
main()
在操作中:
Enter city followed by temperature: NYC 101
Enter city followed by temperature: HK 115
Enter city followed by temperature: stop
{'NYC': '101', 'HK': '115'}