0

I'm trying to initialize a list of empty dictionaries to be filled up later.

Tried using the multiplication operand:

x=2*[{}]

This apparently creates a list with two references that point to the same dictionary object, so that each thing I do to each dictionary gets done to all:

>>> 
>>> x=2*[{}]
>>> x
[{}, {}]
>>> x[0] is x[1]
True
>>> x[0].update({'foo':[]})
>>> x
[{'foo': []}, {'foo': []}]
>>> 
>>> 
>>> y=2*[{}]
>>> y
[{}, {}]
>>> y[0]['bar']=[]
>>> y
[{'bar': []}, {'bar': []}]
>>> 
>>> 
>>> w=2*[{}]
>>> w
[{}, {}]
>>> w[1][1]=1
>>> w
[{1: 1}, {1: 1}]
>>> 

If I assign without the multiplication operand, then I get the behaviour I want:

>>> z=[{},{}]
>>> z
[{}, {}]
>>> z[1][1]=1
>>> z
[{}, {1: 1}]
>>> 

But in my actual code I do not know before runtime how big the list will be!

So, two questions: Is this expected, or a bug in the language? How do I initialize a list to be like the z variable without knowing its size when I write the code?

Context:

Python 3.3.4. Using xlrd to parse a MS Excel spreadsheet. The spreadsheet has several header lines spread whithin the data, each changing the meaning of the data between it and the next header line. I want to loop over the lines filling each dict with the data using the correct (nearest above) headers as keys.

A possible workaround would be to hardcode the list length to the number of lines of this spreadsheet, but that introduces a maintenance issue of requiring a code change every time that number changes.

Thanks for any help.

Emilio M Bumachar
  • 2,532
  • 3
  • 26
  • 30

1 Answers1

3

You need to use a loop.

x = [{} for _ in range(z)]
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895