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.

0

1 Answer 1

4

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

test_dict = dict((x, dict()) for x in ['k1', 'k2'])
Sign up to request clarification or add additional context in comments.

1 Comment

Apparently there is no way to pass an expression to dict.fromkeys. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.