6

I'm having some trouble adding a key-value pair to a nested dictionary. The new pair seems to be getting added to ALL entries in the outer dictionary, instead of just the nested dictionary that I want.

Here's an example:

mykeys = ['key1', 'key2', 'key3']
mydictionary = dict.fromkeys(mykeys, {})
mydictionary['key1']['subkey1'] = 'value1'
mydictionary

I'm expecting to see the following, with 'subkey1' only being added to the 'key1' dictionary:

{'key1': {'subkey1': 'value1'},
 'key2': {},
 'key3': {}}

Instead, it adds the subkey1/value1 pair to every element of the outer dictionary:

{'key1': {'subkey1': 'value1'},
 'key2': {'subkey1': 'value1'},
 'key3': {'subkey1': 'value1'}}

Why is this the case, and how can I re-write my code to fix this mistake?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Sam
  • 89
  • 2
  • 8

1 Answers1

4

mydictionary['key1'] = {'subkey1': 'value1'}

trandatnh
  • 351
  • 8
  • 26