python - Create a list of empty dictionaries -


i want create list of variable length containing empty directories.

n = 10 # size of list foo = [] _ in range(n)     foo.append({}) 

would same way, or there like?

a = [{}*n] 

list comprehensions rescue!

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

there no shorter notation, afraid. in python 2 use xrange(n) instead of range(n) avoid materializing useless list.

the alternative, [{}] * n creates list of length n one dictionary, referenced n times. leads nasty surprises when adding keys dictionary.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -