Adding key-value pair to a nested dictionary

Viewed 5386

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?

1 Answers

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

Related