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?
>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)