E
E
enGuardian2016-04-06 00:36:25
Python
enGuardian, 2016-04-06 00:36:25

How to fill in the list of dictionaries correctly?

There is one bug related to filling in the list of dictionaries.
In the loop, the dictionary is filled, added to the list. At the end of the iteration, the dictionary is cleared to fill with data on the next iteration, but the list is also cleared. As a result, when the loop exits, the list is empty.

Python 2.7.10 (default, Sep  8 2015, 17:21:32) 
[GCC 5.1.1 20150618 (Red Hat 5.1.1-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> list = []
>>> d = {}
>>> d[1] = "1"
>>> d[2] = "2"
>>> list.append(d)
>>> d
{1: '1', 2: '2'}
>>> list
[{1: '1', 2: '2'}]
>>> d.clear()
>>> d
{}
>>> list
[{}]

CHADNT?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
enGuardian, 2016-04-06
@enGuardian

the answer was found: generate a copy of the dictionary and already shove it into the list
list.append(d.copy())

A
Alexey, 2016-04-06
@alsopub

Apparently, you added a link to "d" in "list", then cleared "d", it remained in "list", but already empty.
Notice the [{}], instead of just [].
Try extend instead of append.

A
Alexander, 2016-04-06
@fireSparrow

It's not a bug, that's how it should be.
I advise you to read about data types in python - otherwise you will regularly stumble upon such "bugs".
The bottom line is that all data types are divided into mutable and immutable, and they will behave differently when assigned.
For mutable data types, when you assign, you DO NOT copy the contents of another variable into the variable, but simply pass a reference to the same memory area into it.
That is, if you do this:
a = {some_dictionary}
b = a
then both b and a will refer to the same memory area, and when you change one of these dictionaries, the second will change in the same way. Because it's actually the same dictionary, just under two different names.
With the append method, this works similarly - that is, it does not make a copy of the dictionary, adding it to the list, but simply enlists the SAME dictionary into the list.
As already mentioned above, you need to force a copy of the dictionary, and then insert it into the list.
But, IMHO, it's safer to use not copy(), but deepcopy().

A
abs0lut, 2016-04-06
@abs0lut

There is one bug

this is not a bug, but a misunderstanding of how data structures work in python
why not create a new dictionary at each iteration?
the list is not cleared, curly braces are left in the same place. This is a list with one element

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question