Create a list of empty dictionaries

dictionary, list, python

Solution

List comprehensions to the rescue!

foo = [{} for _ in range(n)]

There is no shorter notation, I am afraid. In Python 2 you use `xrange(n)` instead of `range(n)` to avoid materializing a useless list.

The alternative, `[{}] * n` creates a list of length `n` with only one dictionary, referenced `n` times. This leads to nasty surprises when adding keys to the dictionary.

Problem

I want to create a list of variable length containing empty directories. ``` n = 10 # size of list foo = [] for _ in range(n) foo.append({}) ``` Would you do this the same way, or is there something like? ``` a = [{}*n] ```

Original source