Can someone explain this behavior for me?
mapping = dict.fromkeys([1, 2, 3], [])
objects = [{'pk': 1}, {'pk': 2}, {'pk': 3}]
for obj in objects:
pk = obj['pk']
mapping[pk].append(obj)
print mapping
# expected: {1: [{'pk': 1}], 2: [{'pk': 2}], 3: [{'pk': 3}]}
# got: {1: [{'pk': 1}, {'pk': 2}, {'pk': 3}], 2: [{'pk': 1}, {'pk': 2}, {'pk': 3}], 3: [{'pk': 1}, {'pk': 2}, {'pk': 3}]}
I’m attempting to map the dicts in objects to another dict whose keys are properties of the original dict. Assume the objects list contains several objects of each unique PK (the reason I’m not just using map here).
That’s because in:
[]is evaluated once, so each key has the same list as value. Try usingcollections.defaultdictinstead.