How to Create a List of Dictionaries in Python?

Problem: Say, you have a dictionary {0: 'Alice', 1: 'Bob'} and you want to create a list of dictionaries with copies of the original dictionary: [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}].

d = {0: 'Alice', 1: 'Bob'}

dicts = [{**d} for _ in range(3)]
print(dicts)
# [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]

You use list comprehension with a “throw-away” loop variable underscore _ to create a list of 3 elements. You can change the value 3 if you need more or fewer elements in your list.

The expression {**d} unpacks all (key, value) pairs from the original dictionary d into a new dictionary. For more information about the unpacking operator, see this Finxter blog tutorial.

The resulting list contains copies of the original dictionary. If you change one, the others won’t see that change:

dicts[0][2] = 'Frank'
print(dicts)
# [{0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]

Only the first dictionary in the list contains the new key value pair (2: 'Frank') which proves that the dictionaries don’t point to the same object in memory. This would be the case if you’d use the following method of copying a list with a single dictionary:

d2 = {0: 'Alice', 1: 'Bob'}

dicts2 = [d2] * 3
print(dicts2)
# [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]

The method looks right but all three dictionaries are essentially the same:

dicts2[0][2] = 'Frank'
print(dicts2)
# [{0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob', 2: 'Frank'}]

If you change one, you change all.

You can see this effect yourself in the following memory visualizer tool:

Exercise: change the method to the correct one so that the change affects only the first dictionary!

Related articles: How to create a Python list?

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!