Creating a nested dictionary in a for loop

  dictionary, python

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.

Source: Python Questions

LEAVE A COMMENT