Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange python dict behavior

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

like image 928
Aaron Avatar asked Mar 30 '26 00:03

Aaron


1 Answers

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.

like image 173
soulcheck Avatar answered Apr 02 '26 05:04

soulcheck