Create A List Of Empty Dictionaries
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
Solution 1:
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.
Post a Comment for "Create A List Of Empty Dictionaries"