1

I have some confusion regarding python's append vs. extend on a list which is supposed to contain dictionaries:

holder = []

element = {}

element["id"] = 1
element["value"] = 2

holder.append(element)

print(holder)

prints as expected [{'id': 1, 'value': 2}]

however if I use: holder.extend(element) instead of holder.append(element) the output will be: ['id', 'value']

Can someone explain me why? (append vs. extend does not apply for this)

Community
  • 1
  • 1
Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167

3 Answers3

5

list.extend() takes an iterable and appends all elements of the iterable. Dictionary by default iterates over its keys, so all the keys are appended to the list.

list.append() takes the object as is and adds it to the list, which is exactly what happend in your code.

Danstahr
  • 4,190
  • 22
  • 38
1

Doing append, it adds a thing element, the dictionary.
Doing extend, it adds each thing of element if element is a list:

>>> element = {}
>>> element["id"] = 1
>>> element["value"] = 2
>>> list(element)
['id', 'value']

In the case of dictionary, it iterates on the the keys.

fredtantini
  • 15,966
  • 8
  • 49
  • 55
0

Appending a copy of the dictionary to a list seems a better approach especially when creating a list of dictionaries in a loop.

Ref. Appending a dictionary to a list in a loop

holder = []

element = {}

element["id"] = 1
element["value"] = 2
for i in range(10):
    element['value'] = i*2
    holder.append(element.copy())

print(holder)
Joaquim
  • 380
  • 4
  • 10