Home > OS >  Why does append() and = give different results when I want to add a dictionary into a list in Pytho
Why does append() and = give different results when I want to add a dictionary into a list in Pytho

Time:07-16

I want to append a dictionary germany into a list travel_log.

travel_log = [
{
  "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
}]
germany = {
  "country": "Germany",
  "visits": 5,
  "cities": ["Berlin", "Hamburg", "Stuttgart"]
}

When I use travel_log = germany, the result is

[{'country': 'France', 'visits': 12, 'cities': ['Paris', 'Lille', 'Dijon']}, 'country', 'visits', 'cities'].

The values in germany disappeared.

But when I use travel_log.append(germany), the result is

[{'country': 'France', 'visits': 12, 'cities': ['Paris', 'Lille', 'Dijon']}, {'country': 'Germany', 'visits': 5, 'cities': ['Berlin', 'Hamburg', 'Stuttgart']}]

This is the correct one.

Why these two results are diffrent?

CodePudding user response:

Because = extends the list with another iterable, and iterating over a dict iterates over the keys (try print(list(germany))).

You'd get the same effect with travel_log.extend(germany).

.append(x) doesn't iterate over x, it just appends it as-is to the list.

CodePudding user response:

The two results are different because = and .append are designed to do completely different things.

.append adds a value to the end of a list. For example:

a = [1, 2, 3]
a.append(4)
print(a)
# => [1, 2, 3, 4]

= adds all the values from another iterable to the end of the list - it does the same as .extend. If you tried to do a = 4 in the example above, it would error as 4 is not an iterable.

However, you are adding a dictionary, and a dictionary is an iterable - iterating over it will iterate over its keys. Hence = here does not error, but instead adds all the keys of the dictionary to the list (without erroring).

  • Related