Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group list of dictionaries by value [duplicate]

Tags:

python

I have a list of dictionaries. How can i group that list by valaues.

list = [{a:1},{b:2},{c:1},{d:3},{e:2}]

Now my result should be like below

1:a,c
2:b,e
3:d

I tried using groupby from itertools. But i couldn't get the required result. I am using python 2.7.

Could you help me achieve this?

like image 395
Vasantha Kumari Avatar asked Mar 09 '18 09:03

Vasantha Kumari


2 Answers

If you want to use groupby, the list has to be sorted by the same key you want to group by.

>>> lst = [{'a':1}, {'b':2}, {'c':1}, {'d':3}, {'e':2}]

>>> keyfunc = lambda d: next(iter(d.values()))

>>> sorted(lst, key=keyfunc)
[{'a': 1}, {'c': 1}, {'b': 2}, {'e': 2}, {'d': 3}]

>>> {k: [x for d in g for x in d] 
...  for k, g in itertools.groupby(sorted(lst, key=keyfunc), key=keyfunc)}
{1: ['a', 'c'], 2: ['b', 'e'], 3: ['d']}
like image 149
tobias_k Avatar answered Sep 19 '22 18:09

tobias_k


Here's a possible solution without using any library.

def get_dict(list):
    res = {}

    for elem in list:
        k, v = elem.keys(), elem.values()

        if v[0] in res:
            res[v[0]].append(k[0])
        else:
            res[v[0]] = [k[0]]

    return res

With a list like yours, this would output a dictionary with the following format:

{ 1:[a,c], 2:[b, e], 3:[c] }

This is considering you're always going to have the same format as input. If not, you could just adjust what is read and saved.

like image 40
Berbus Avatar answered Sep 19 '22 18:09

Berbus