loading...

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

Micheal Ojemoron on February 22, 2020

Using dict.get How often have you aggregated an item by its group like this: ar= [1,1,3,1,2,1,3,3,3,3] pairs = {} for i in ar: if ... [Read Full]
markdown guide
 

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)
 

Diddo the swap from

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

to

for item in items:
   ...
 

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

 

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

 

I love the Counter object. I've had a rest API getting bogged down with pandas trying to count something and it took a few seconds for each response. Counter was just a few ms.

 
 
 
code of conduct - report abuse