Ian Gullett
Ian Gullett

Reputation: 137

Creating a nested dictionary in a for loop

I'm trying to create a nested dictionary and don't understand the output I'm getting.

The code I've run is:

import numpy as np

io_dict = dict.fromkeys(['a', 'b'])
channel_dict = dict.fromkeys(['ch1', 'ch2'])

io_dict['a'] = channel_dict
io_dict['b'] = channel_dict
for channel in channel_dict.keys():
    io_dict['a'][channel] = np.array([1,2,3])
    io_dict['b'][channel] = np.array([5,6,7])
io_dict

This produces the output:

{'a': {'ch1': array([5, 6, 7]), 'ch2': array([5, 6, 7])},
 'b': {'ch1': array([5, 6, 7]), 'ch2': array([5, 6, 7])}}

However, I was expecting:

{'a': {'ch1': array([1, 2, 3]), 'ch2': array([1, 2, 3])},
 'b': {'ch1': array([5, 6, 7]), 'ch2': array([5, 6, 7])}}

Any help would be greatly appreciated.

Upvotes: 2

Views: 440

Answers (1)

Udipta kumar Dass
Udipta kumar Dass

Reputation: 151

Both of your dictionaries which are io_dict['a'] and io_dict['b'] are from same dictionary, so when ever you are updating the above two dictionaries, its updating the same from the back end so you are getting such kind of error. Going to view of compiler, as you have assigned channel_dict to both io_dict['a'] and io_dict['b'], so these two works as a shortcut that refers to the same memory location and when ever you are updating one then both gets updated.

But if we will use io_dict['a'] = channel_dict.copy() and io_dict['b'] = channel_dict.copy() instead, then the compiler will take different memory location for both of your dictionaries which will fulfill your requirment.

Your completed code will be,

import numpy as np

io_dict = dict.fromkeys(['a', 'b'])
channel_dict = dict.fromkeys(['ch1', 'ch2'])

io_dict['a'] = channel_dict.copy()
io_dict['b'] = channel_dict.copy()
for channel in channel_dict.keys():
    io_dict['a'][channel] = np.array([1,2,3])
    io_dict['b'][channel] = np.array([5,6,7])
print(io_dict)

Upvotes: 2

Related Questions