Skip to content
Advertisement

itertools group by multiple keys

I am using itertools to group by a dictionary key using the below:

host_data = []
for k,v in itertools.groupby(temp_data, key=lambda x:x['device_id'])
    d = {}
    for dct in v:
        d.update(dct)
    host_data.append(d) 

However I would like to group by ‘device_id’ and ‘port_id’ if possible, how can I add an additional key to the grouping?

Advertisement

Answer

Just use a tuple as key:

itertools.groupby(temp_data, key=lambda x:(x['device_id'], x['port_id']))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement