This is my first question on Stack Overflow.
I want to add a new dictionary at the end of an existing list with multiple dictionaries (see example below):
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
new_country = {
"country": country,
"visits": int(visits),
"cities": list_of_cities,
}
new_country
needs to be added to the list of travel_log
, but for a certain reason if I write:
travel_log += new_country
It does not work, while
travel_log.append(new_country)
will give the correct result.
I thought until now that the +=
operator could be used in lists quite easily, but I am now a bit confused. Thank you in advance for your answers.
The +=
operator is used to extend a list with the elements of another iterable. However, when you want to add a single element to a list (not an iterable), you should use the append method.
so if you use +=
with 2 list it will concatenate them.
+=
: Extends the list with the elements of another iterable.
append()
: Adds a single element to the end of the list.
That is why append
is working.
example:
travel_log = [ { "country": "France", "visits": 12, "cities": ["Paris", "Lille", "Dijon"] }, { "country": "Germany", "visits": 5, "cities": ["Berlin", "Hamburg", "Stuttgart"] }, ]
new_country = [{ "country": country, "visits": int(visits), "cities": list_of_cities, }]
travel_log+=new_country
This should work using +=
and if you want to use exact with append it will be:
travel_log.append(new_country[0])
otherwise you will have a list appended instead of a dict