'Function : Updating & printing a dictionary with the most recent values
I've created a function : A dictionary which takes in city name and country name to which the city belongs to. Currently the code just returns a dictionary after each iteration with city name and country name after taking inputs using the input(). I'm trying to update the code (no success so far) so that a new dictionary is printed after each iteration with updated dictionary which returns an output like
{'city' : 'berlin', 'country' : 'germany',
'city' : 'paris', 'country' : 'france',}
The code is as follows :
def city_country(city_name, country_name):
pair = {'City': city_name, 'Country': country_name}
return pair
active = True
while active:
user_city = input("Enter city name : ")
if user_city == 'q':
break
user_country = input("Enter country name : ")
if user_country == 'q':
break
new_pair = city_country(user_city, user_country)
print(new_pair)
Solution 1:[1]
city_country_dict = {}
active = True
while active:
user_city = input("Enter city name : ")
if user_city == 'q':
break
user_country = input("Enter country name : ")
if user_country == 'q':
break
new_pair = city_country(user_city, user_country)
#=================================
city_country_dict.update(new_pair)
#=================================
print(city_country_dict)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Henshal B |
