Skip to content
Advertisement

Nested dictionary incorrectly populating all top level key-value pairs with same values

I am having a strange issue where indexing a nested dictionary correctly results in the same value being assigned for all top level keys (k’s). Below is the whole chunk of code.

JavaScript

Below is the output of this block:

JavaScript

You can see by the print statements that after the first iteration of the middle loop, all top level keys have been assigned the same values, even though the line reads as scores_by_n[k][j]. Please help me understand how this issue is occurring.

Advertisement

Answer

Create new dict by this instead.

JavaScript

The issue is caused by using the fromkeys() function to create the outermost dictionary and specifying the same dictionary object as the value for all keys. This means that all keys in the outermost refer to the same dictionary object, so any changes made to the object were reflected for all keys.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement