0

I have a dictionary indexed by 201 integer keys (0..200). the value for each of these keys is a list. generated with the code below:

dictionary=dict.fromkeys(range201,[])

i am getting this strange behaviour when i try to append items to the list belonging to one specific index, if i do this:

dictionary[1].append("foo")

i would expect this:

>>dictionary
{0:[], 1:["foo"],2:[],...}

but instead i end up with this:

>>dictionary
{0:["foo"], 1:["foo"],2:["foo"],...}

to clarify a bit the context in which the operation is performed, i am enumerating a list of values that can be None or float, i want to skip the None and append the float to the list corresponding to the enumerate index:

for i, value in enumerate(valuesList):
    if value is None:
        continue
    dictionary[i].append(value)

this is behaviour is independent of which integer index i use, and i end up with the same values at all indices. I could use a list of lists and achieve the same result i think. but i wanted to understand this behaviour.

Tito Candelli
  • 217
  • 1
  • 10

1 Answers1

1

This is the normal behavior. All the entry of your dictionary where initialized with a reference to the same list. So when appending an element using one key, as all the key are pointing the same list, the modification is applied to all the entries of the dic.

Try this instead :

dictionary={}
for i in range(201):
    #the loop make the list.__init__() (i.e. the []) being called 200 times
    dictionary[i] = []

dictionary[1].append("foo")
print dictionary
Arthur Vaïsse
  • 1,551
  • 1
  • 13
  • 26