1

I am trying to create a ordered dic for a given set of keys. I structure i am going for is `

     OrderedDict([('A', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 
                  ('B', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 
                  ('C', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 
                  ('D', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])])`

This is being created by the following function.

d = OrderedDict.fromkeys(keys, [0 for _ in range(10)])

I am successfully getting the required structure.

The problem is the values of the dict all are being created as references. Meaning when i try to do the following d['A'][1] = "11111" it changed values of every key given. i get the result as the following.

    OrderedDict([('A', [0, '11111', 0, 0, 0, 0, 0, 0, 0, 0]), 
                 ('B', [0, '11111', 0, 0, 0, 0, 0, 0, 0, 0]), 
                 ('C', [0, '11111', 0, 0, 0, 0, 0, 0, 0, 0]), 
                 ('D', [0, '11111', 0, 0, 0, 0, 0, 0, 0, 0])])

i did try deepcopy but didnt really help. the work around i currently have is

d['A'] = d['A'][:]

i dont really like the above soln because i have about 6mil keys and values.. so doing this is a bit of a hassle.

I would like to know a better way of doing this.. and also why this is happening.

Yatish Kadam
  • 454
  • 2
  • 11

1 Answers1

2

The classmethod fromkeys uses the same default value for all dictionary keys.

To avoid that, specify a new instance for each key:

d = OrderedDict((k, [0]*10) for k in keys)
wim
  • 338,267
  • 99
  • 616
  • 750