Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this Python logic update all keys in the dictionary

Please see Python example below:

data = dict.fromkeys(string.ascii_lowercase, [])
children = ["one", "two"]
for child in children:
    current_key = child[0].lower()
    data[current_key].append(child)

print("data: ", data)

Why does this update all keys with all values from the children list?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The reason why all keys are updated with all values from the children list is because the fromkeys method of the dict class creates a dictionary where all keys share the same reference to a single list object. Therefore, when you append values to one key’s list, you’re actually modifying the same list object that is referenced by all keys.

To fix this, you need to create a new list object for each key. You can do this by using a dictionary comprehension instead of the fromkeys method. Here’s the corrected code:

import string

data = {key: [] for key in string.ascii_lowercase}
children = ["one", "two"]

for child in children:
    current_key = child[0].lower()
    data[current_key].append(child)

print("data: ", data)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading