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:
mapping = dict.fromkeys([1, 2, 3], [])
[] is evaluated once, so each key has the same list as value. Try using collections.defaultdict instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With