Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 there something like?

a = [{}*n]
like image 497
Martin Flucka Avatar asked Apr 05 '13 13:04

Martin Flucka


People also ask

How do I create a list of empty dictionaries in Python?

Method #1 : Using {} + "*" operator We can create a list containing single empty dictionary and then multiply it by Number that is size of list. The drawback is that similar reference dictionaries will be made which will point to similar memory location.

How do you create an empty list?

You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed. Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.

How do you initialize a dictionary list?

One way to initialize a Dictionary<TKey,TValue>, or any collection whose Add method takes multiple parameters, is to enclose each set of parameters in braces as shown in the following example. Another option is to use an index initializer, also shown in the following example.


1 Answers

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.

like image 171
Martijn Pieters Avatar answered Oct 17 '22 10:10

Martijn Pieters