RPD
RPD

Reputation: 33

Python: appending dictionaries to a list

This is a simple code to create a list of dictionaries in Python, however the append function in the loop is creating a list instead of the list of dictionaries.

How can I append a dictionary to a list?

data = []
d = { "item1": None,
     "item2": None
     }

for i in range(3):
    d["item1"] = i+1
    d["item2"] = i+2
    data.append(d)

print "data = ", data

The output I am looking for is

d = [
            {
                "item1": 1,
                "item2": 2
            },        
            {
                "item1": 2,
                "item2": 3
            },        
            {
                "item1": 3,
                "item2": 4
            }
         ]

Upvotes: 1

Views: 504

Answers (2)

awesoon
awesoon

Reputation: 33651

You could simply append new dictionary:

for i in range(3):
    data.append({"item1": i+1, "item2": i+2})

Or, even better, use list comprehension:

data = [{"item1": i+1, "item2": i+2} for i in range(3)]

Upvotes: 1

Anand S Kumar
Anand S Kumar

Reputation: 90889

You are only adding the reference to d into your data list, but the d reference never changes, hence when you change d's value in the next iteration, previously added dictionaries in the list changes as well.

Try -

data = []
for i in range(3):
    d = {}
    d["item1"] = i+1
    d["item2"] = i+2
    data.append(d)
print "data = ", data

Upvotes: 1

Related Questions