Search code examples
pythonpython-itertools

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?


Solution

  • Just use a tuple as key:

    itertools.groupby(temp_data, key=lambda x:(x['device_id'], x['port_id']))