Reputation: 147
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()
Upvotes: 1
Views: 709
Reputation: 113834
To solve the immediate issue, replace:
city[valu] = city[valu]+1
With:
city[valu] = city.get(valu, 0) + 1
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
.
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'}
Upvotes: 1
Reputation: 113915
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
Upvotes: 2