KeyError with dictionaries

705 views Asked by At

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

There are 2 answers

3
John1024 On BEST ANSWER

To solve the immediate issue, replace:

        city[valu] = city[valu]+1

With:

        city[valu] = city.get(valu, 0) + 1

Explanation

city.get(valu) is just like city[valu] except that it provides a default value of None if the key doesn't exist. city.get(valu, 0) is similar but it sets the default value to 0.

Complete Program

Guessing at what you wanted, here is a rewrite of the code:

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

In operation:

Enter city followed by temperature: NYC 101
Enter city followed by temperature: HK 115
Enter city followed by temperature: stop
{'NYC': '101', 'HK': '115'}
2
inspectorG4dget On

Change your for-loop to look like this:

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

You get an error because the first time around, valu is not a key in city. As a result, city[valu] fails. Setting it to 0 (or some other default value) when the key doesn't exist will fix your problem