0

Value assignment leaking over keys when using a dictionary of dictionaries.

Used the fromkeys() function to create the outer dictionary.

Environment: Python 3.6.3

sample_dict = dict.fromkeys(
    [1,0], 
    {}
)
sample_dict[1]['a'] = 1
print(sample_dict)

Output:

{1: {'a': 1}, 0: {'a': 1}}

As you can see, the value gets duplicated for key 0 even when I am only assigning it to key 1.


I tried this and it worked as expected:

sample_dict = dict.fromkeys(
    [1,0]
)
sample_dict[1] = {}
sample_dict[1]['a'] = 1
print(sample_dict)

Output:

{1: {'a': 1}, 0: {}}

Is it wrong to nest dictionaries when using the fromkeys() function?

Omkar Neogi
  • 675
  • 2
  • 9
  • 30
  • Hey Jean-Francois, thank you so much for answering so promptly! Could you give me an explanation as to why this doesn't work please? For whoever might benefit from this information, the solution in the other (the original) question worked for me. – Omkar Neogi Nov 13 '17 at 05:00
  • Please read ALL the answers to the linked question. Specifically, this one states why what you originally tried does not work: https://stackoverflow.com/a/44506022/1399279. – SethMMorton Nov 13 '17 at 05:45

0 Answers0