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
  • 15,542
  • 10
  • 50
  • 67

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
  • 776,304
  • 153
  • 1,341
  • 1,358