So I have been practicing some coding in Python. I came to a task where I was supposed to add a dictionary to an existing list (which had dictionaries).
The given function (at the end) works, but when I tried to write the following (in the function)
travel_log.append(add_new_country)
instead of
travel_log.append(country)
travel_log.append(visits)
travel_log.append(cities)
and then try to print out travel_log, I would get the following (look at the last dictionary in the list):
[{'country': 'France', 'visits': 12, 'cities': ['Paris', 'Lille', 'Dijon']}, {'country': 'Germany', 'visits': 5, 'cities': ['Berlin', 'Hamburg', 'Stuttgart']},<function add_new_country at 0x7fefd60e8310>]
Can somebody explain why does that happen?
Full code:
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
def add_new_country(country,visits,cities):
travel_log.append(country)
travel_log.append(visits)
travel_log.append(cities)
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)
CodePudding user response:
You need to create a dictionary and add it to travel_log
(list),
def add_new_country(country,visits,cities):
d = {'country': country, 'visits': visits, 'cities': cities}
travel_log.append(d)