How to append dictionaries in Python (All versions)?
Have you ever felt that Python’s flexible data structure list is not letting you do what you want? Well, we experienced it. We had great leanings while tackling this issue in Python. This article explains how we solved this issue.
It all started when we were executing crucial aspect of the project for one of our client. We developed a code snippet which had functionality as similar as to the below example snippet.
Aim here was to create a list of distinct dictionaries inside for loop.
We thoroughly checked the logic and confirmed that the logic is alright. Then what was causing this unexpected behavior of list?
Here is assessment of above issue:
The dictionary we are using inside the for loop i.e. “y” is referenced every time we assign something new to it. After the final assignment, the object referenced(y) holds the last assigned value. Since the list contains many instances of same referenced object(y), all the instances contain the last assigned value. So as a reason, the output of the above snippet is actual output rather than Expected output.
Note: Here, ‘referenced’ means call by reference i.e. calling by memory address.
Below is the detailed understanding of this issue through diagrammatic representation:
Every problem has a solution! The above problem could be resolved using following approach as follows:
We used Python’s in-built copy method. This method creates as many dictionaries as the range.
Note: The dictionary objects inside the list are now different to each other i.e. all of them have their own memory addresses.
So, this way we you can use Python’s flexible data structure. We will strive to identify more of Python’s assets and make you informed. In case you want to know more about this, you can comment your specific question in the comment section of this article.