Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add dictionary in List in Python but, data is duplicated

data = []
dic = dict.fromkeys(['a', 'b', 'c'], 0)

value = 1
for i in range(3):
    key = list(dic.keys())
    for j in range(len(dic)):
        dic[key[j]] = value
        value += 1
    data.append(dic)
    
for i in data:
    print(i)

In this code, I expexted like this.

{1, 2, 3}
{4, 5, 6}
{7, 8, 9}

but the result is

{7, 8, 9}
{7, 8, 9}
{7, 8, 9}

How can i fix this code to get result that i expected?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Instead of :

    data.append(dic)

Use:

    data.append(dic.copy())

This will create a new object, instead of adding a reference to dic to your list.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading