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()
To solve the immediate issue, replace:
With:
Explanation
city.get(valu)
is just likecity[valu]
except that it provides a default value ofNone
if the key doesn't exist.city.get(valu, 0)
is similar but it sets the default value to0
.Complete Program
Guessing at what you wanted, here is a rewrite of the code:
In operation: