DEV Community

Discussion on: Pythonic way to aggregate or group elements in a list using dict.get and dict.setdefault

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

This is just too magical, and hard to understand.

items_by_type = {}
for item in items:
    items_by_type.setdefault(item.type, list()).append(item)

A less magical version is defaultdict (from collections)

items_by_type = defaultdict(list)
for item in items:
    items_by_type[item.type].append(item)
Collapse
 
mojemoron profile image
Micheal Ojemoron • Edited

You are right😁, fortunately there are several ways to do things in Python. I am more concerned about using dictionary methods. Thank you

Collapse
 
waylonwalker profile image
Waylon Walker • Edited

Diddo the swap from

for i in range(len(items)):
   ...

to

for item in items:
   ...
Collapse
 
mojemoron profile image
Micheal Ojemoron

you are absolutely right, I have updated the code. Thanks