Python convert list of dictionaries to dict of key, values as list

I have a list of objects as below :

avariable = [{'id':1,'color':'pink'},{'id':1,'color':'blue'},{'id':2,'color':'green'}]

I want to convert it to :

{
"1" : [{'id':1,'color':'pink'},{'id':1,'color':'blue'}],
"2" : [{'id':2,'color':'green'}]
}

How to achieve this output, please help.

2 answers

  • answered 2018-01-14 10:00 Vivek Kalyanarangan

    As the suggestions have spoken, you need itertools.groupby -

    from itertools import groupby
    
    avariable = [{'id':1,'color':'pink'},{'id':1,'color':'blue'},{'id':2,'color':'green'}]
    groups = []  
    uniquekeys = []  
    for k, g in groupby(sorted(avariable, key=lambda x: x['id']), lambda x: x['id']): 
        # Store group iterator as a list 
        groups.append(list(g))        
        uniquekeys.append(k)
    
    print({ str(i):j for i, j in zip(uniquekeys, groups) })
    

    The output -

    {'1': [{'id': 1, 'color': 'pink'}, {'id': 1, 'color': 'blue'}], '2': [{'id': 2,
    'color': 'green'}]}
    

  • answered 2018-01-14 10:00 NinjaElvis

    Without using any additional libraries.

    avariable = [{'id':1,'color':'pink'},{'id':1,'color':'blue'},{'id':2,'color':'green'}]
    
    new_dict = {}
    keys = set([i['id'] for i in avariable])
    
    for key in keys:
        temp = []
        for l in avariable:
            if l['id'] == key:
                temp.append(l)
            new_dict[key] = temp
    
    
    print(new_dict)
    {1: [{'color': 'pink', 'id': 1}, {'color': 'blue', 'id': 1}],
     2: [{'color': 'green', 'id': 2}]}
    

    one liner (dictionary comprehension):

    new_dict = {key: [l for l in avariable if l['id'] == key] for key in set([i['id'] for i in avariable])}