How to append dictionaries in Python (All versions)?

How to append dictionaries in Python (All versions)?
Python For Loop
Swaroop Buddha
Posted by on August 2, 2017 in Blog

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.

python for loop

We thoroughly checked the logic and confirmed that the logic is alright. Then what was causing this unexpected behavior of list?

Analysis:

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:

 

Python Dictionary

Every problem has a solution! The above problem could be resolved using following approach as follows:

Solution:

We used Python’s in-built copy method. This method creates as many dictionaries as the range.

 

concatenate dictionary in python

Note: The dictionary objects inside the list are now different to each other i.e. all of them have their own memory addresses.

Diagrammatic representation:

How to append dictionaries in Python (All versions)?

 

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.