1

How can I get around this limitation:

>>> test_dict = dict.fromkeys(['k1', 'k2'], dict())
>>> test_dict['k1']['sub-k1'] = 'apples'
>>> test_dict
{'k2': {'sub-k1': 'apples'}, 'k1': {'sub-k1': 'apples'}}

I want each of the keys k1 and k2 to have a new dictionary instance, not the same one.

sholsapp
  • 14,714
  • 10
  • 46
  • 64

1 Answers1

4

Then don't give them the same instance of the object.

test_dict = dict((x, dict()) for x in ['k1', 'k2'])
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325