How to groupby list of dictionary in python?

Given the list

l = [('a', 1), ('b', 2), ('a', 1), ('a', 2), ('c', 5), ('b', 3)]

how do I get the dictionary

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

in Python?

Edit: I was looking for a functional solution (using only 1 expression).

asked Oct 25, 2016 at 8:33

2

You may use the collections.defaultdict(). Alternatively, in case you do not want to import collections , you may achieve the same behavior with normal dict using dict.setdefault() as:

>>> my_dict = {}
>>> l = [('a', 1), ('b', 2), ('a', 1), ('a', 2), ('c', 5), ('b', 3)]
>>> for k, v in l:
...     my_dict.setdefault(k, []).append(v)
...
>>> my_dict
{'a': [1, 1, 2], 'c': [5], 'b': [2, 3]}

answered Oct 25, 2016 at 8:57

How to groupby list of dictionary in python?

Moinuddin QuadriMoinuddin Quadri

44.6k12 gold badges92 silver badges118 bronze badges

After defining

from itertools import *

def group(iterable, key, value = lambda x: x):
    return dict((k, list(map(value, values))) for k, values in groupby(sorted(iterable, key = key), key))

use group(l, key = lambda x: x[0], value = lambda x: x[1])).

answered Oct 25, 2016 at 8:33

Using defaultdict from the collections module. You can iterate the list and extract the (key, value) pairs from the tuples in the list and build your dictionary.

from collections import defaultdict

l = [('a', 1), ('b', 2), ('a', 1), ('a', 2), ('c', 5), ('b', 3)]

def dict_my_list(lst):
    d = defaultdict(list)
    for key, value in lst:
        d[key].append(value)
    return d

print dict_my_list(l)  # {'a': [1, 1, 2], 'c': [5], 'b': [2, 3]}

answered Oct 25, 2016 at 8:40

Inbar RoseInbar Rose

39.8k24 gold badges82 silver badges128 bronze badges

Here is a simple solution to your problem using dict()

l = [('a', 1), ('b', 2), ('a', 1), ('a', 2), ('c', 5), ('b', 3)]
ll = dict()
for key,value in l:
    if key in ll:
        ll[key].append(value)
    else:
        ll[key] = list()
        ll[key].append(value)

print ll  # {'a': [1, 1, 2], 'c': [5], 'b': [2, 3]}

answered Oct 25, 2016 at 8:48

How to groupby list of dictionary in python?

User_TargaryenUser_Targaryen

3,9603 gold badges27 silver badges48 bronze badges

How to groupby list of dictionary in python?

The itertools function in Python provides an efficient way for looping lists, tuples and dictionaries. The itertools.groupby function in itertools will be applied in this tutorial to group a list of dictionaries by a particular key.

To illustrate how this works, we will look at a list of students info (in dictionaries) and try to group these by “class” key such…

Sometimes, we want to use groupby results to dictionary of lists with Python Pandas.

In this article, we’ll look at how to use groupby results to dictionary of lists with Python Pandas.

How to use groupby results to dictionary of lists with Python Pandas?

To use groupby results to dictionary of lists with Python Pandas, we can us the apply and to_dict methods.

For instance, we write

df.groupby('Column1')['Column3'].apply(list).to_dict()

to call groupby with 'Column1 to group the df data frame values by Column1.

And then we get the values from Column3 from the grouped results.

And then we call apply with list to convert the result to a list.

Finally, we call to_dict to convert the dict to a dictionary.

Conclusion

To use groupby results to dictionary of lists with Python Pandas, we can us the apply and to_dict methods.

Web developer specializing in React, Vue, and front end development.

View Archive

How to group dictionary in Python?

Method : Using sorted() + items() + defaultdict() This task can be performed by combining the tasks which can be done by above functions. The defaultdict() is used to create a dictionary initialized with lists, items() gets the key-value pair and grouping is helped by sorted().

How do I Groupby a list in Python?

You can group DataFrame rows into a list by using pandas. DataFrame. groupby() function on the column of interest, select the column you want as a list from group and then use Series. apply(list) to get the list for every group.

Can we combine dictionaries if so how?

You can merge two dictionaries using the | operator. It is a very convenient method to merge dictionaries; however, it is only used in the python 3.9 version or more.

How do you make a list into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.