Problem iterating through dictionaries
I'm trying to iterate through a source dictionary and append the value of each key to the associated key in a destination dictionary. But, for some reason it's appending the value of every key in the source dictionary to each key in the destination dictionary:
source = dict.fromkeys(range(3), 1)
dest = dict.fromkeys(range(3), [])
for key in source:
dest[key].append(source[key])
>>> print(dest)
expected: {0: [1], 1: [1], 2: [1]}
actual: {0: [1, 1, 1], 1: [1, 1, 1], 2: [1, 1, 1]}
This is happening both in version 3.7 and 3.4, and how I loop doesn't seem to matter: I can use a while loop and the same thing happens, I can structure the for loop as for key, value in source.items():, I can copy the values in source to a list and then try to append them one at a time into dest and it still ends up the same way. No matter what I do, it acts like a nested loop and appends every value from source into each key of dest even though I'm not telling it to do anything like that.
What am I doing wrong?
3 comments · 100% upvoted · other discussions
The three dictionary values in
destrefer to the same list object.print(*[id(v) for v in dest.values()], sep=', ')Akerlof [OP] 1 points · Nov 2018
Yep, that's what it was. I didn't think through
dict.fromkeys()to realize that it would add the same object to every key.
Thanks much!