1

I was attempting to get the user to enter a city and the temperature which would be saved to a dictionary. However, Python keeps telling me that I'm getting a KeyError. Why is this happening and how do i fix this? Thank you.

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()
4

2 回答 2

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当密钥不存在时将其设置为(或其他一些默认值)将解决您的问题

于 2014-11-19T01:49:14.073 回答
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'}
于 2014-11-19T02:08:15.923 回答