Please find the below code for appending a value to a Python dictionary. In the below program our aim is to add a new entry to the existing python dictionary.
#First one is the existing travel log list
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
#Defining a function that will add a new entry to the existing travel log.
def add_new_country(country,visits,cities):
#Below we are creating a dictionary that will take parameters from the function
and append to the travel log.
countrydict = {}
countrydict["country"] = country
countrydict["visits"] = visits
countrydict["cities"] = cities
travel_log.append(countrydict)
#Below we are calling the function that has been created above
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)
Output:

No comments:
Post a Comment