Pandas: Convert GroupBy results to Dictionary of Lists

avatar
Borislav Hadzhiev

Last updated: Apr 12, 2024
4 min

banner

# Table of Contents

  1. Pandas: Convert GroupBy results to Dictionary of Lists
  2. GroupBy results to Dictionary of Lists using a dict comprehension
  3. GroupBy results to Dictionary of Lists using a for loop
  4. Converting the groupby() result to a dictionary of DataFrames

# Pandas: Convert GroupBy results to Dictionary of Lists

To convert the results of a groupby() call in a Pandas DataFrame to a dictionary of lists:

  1. Call the groupby() method on the DataFrame, passing it the specific column as a parameter.
  2. Use square brackets to select the column you want to have as dictionary values.
  3. Convert the result to a dictionary using to_dict().
main.py
import pandas as pd df = pd.DataFrame({ 'Animal': ['Cat', 'Cat', 'Cat', 'Dog', 'Dog', 'Dog'], 'Max Speed': [25, 35, 45, 55, 65, 75] }) print(df) a_dict = df.groupby('Animal')['Max Speed'].apply(list).to_dict() print('-' * 50) # 👇️ {'Cat': [25, 35, 45], 'Dog': [55, 65, 75]} print(a_dict)
The code for this article is available on GitHub

Running the code sample produces the following output.

shell
Animal Max Speed 0 Cat 25 1 Cat 35 2 Cat 45 3 Dog 55 4 Dog 65 5 Dog 75 -------------------------------------------------- {'Cat': [25, 35, 45], 'Dog': [55, 65, 75]}

groupby results to dictionary of lists in pandas dataframe

We used the DataFrame.groupby() method to group the DataFrame by the Animal column.

main.py
a_dict = df.groupby('Animal')['Max Speed'].apply(list).to_dict() # 👇️ {'Cat': [25, 35, 45], 'Dog': [55, 65, 75]} print(a_dict)

The next step is to select the column you want to have as values in the dictionary using bracket [] notation.

The DataFrame.apply() method applies a function along an axis of the DataFrame.

We used the list class to convert each row to a list.

The last step is to call the DataFrame.to_dict() method to convert the resulting DataFrame to a dictionary.

# GroupBy results to Dictionary of Lists using a dict comprehension

You can also use a dict comprehension to convert the results of a GroupBy to a dictionary of lists.

main.py
import pandas as pd df = pd.DataFrame({ 'Animal': ['Cat', 'Cat', 'Cat', 'Dog', 'Dog', 'Dog'], 'Max Speed': [25, 35, 45, 55, 65, 75] }) print(df) a_dict = { key: list(value) for key, value in df.groupby('Animal')['Max Speed'] } print('-' * 50) print(a_dict)
The code for this article is available on GitHub

Running the code sample produces the following output.

shell
Animal Max Speed 0 Cat 25 1 Cat 35 2 Cat 45 3 Dog 55 4 Dog 65 5 Dog 75 -------------------------------------------------- {'Cat': [25, 35, 45], 'Dog': [55, 65, 75]}

convert groupby results to dictionary of lists using dict comprehension

Dict comprehensions are very similar to list comprehensions.

main.py
a_dict = { key: list(value) for key, value in df.groupby('Animal')['Max Speed'] }
They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

On each iteration, we return the key and convert the value to a list to construct the dictionary.

# GroupBy results to Dictionary of Lists using a for loop

You can also use a simple for loop to convert the results of a groupby() call to a dictionary of lists.

main.py
import pandas as pd df = pd.DataFrame({ 'Animal': ['Cat', 'Cat', 'Cat', 'Dog', 'Dog', 'Dog'], 'Max Speed': [25, 35, 45, 55, 65, 75] }) print(df) a_dict = {} for key, value in df.groupby('Animal')['Max Speed']: a_dict[key] = list(value) print('-' * 50) print(a_dict)
The code for this article is available on GitHub

Running the code sample produces the following output.

shell
Animal Max Speed 0 Cat 25 1 Cat 35 2 Cat 45 3 Dog 55 4 Dog 65 5 Dog 75 -------------------------------------------------- {'Cat': [25, 35, 45], 'Dog': [55, 65, 75]}

convert groupby results to dictionary using for loop

We used a for loop to iterate over the GroupBy object and added the current key and value to the new dictionary.

# Converting the groupby() result to a dictionary of DataFrames

If you want to convert the groupby() result to a dictionary of DataFrames, use the dict() class.

main.py
import pandas as pd df = pd.DataFrame({ 'Animal': ['Cat', 'Cat', 'Cat', 'Dog', 'Dog', 'Dog'], 'Max Speed': [25, 35, 45, 55, 65, 75] }) print(df) a_dict = dict(tuple(df.groupby('Animal'))) print('-' * 50) print(a_dict) print('-' * 50) print(type(a_dict['Cat']))
The code for this article is available on GitHub

Running the code sample produces the following output.

shell
Animal Max Speed 0 Cat 25 1 Cat 35 2 Cat 45 3 Dog 55 4 Dog 65 5 Dog 75 -------------------------------------------------- {'Cat': Animal Max Speed 0 Cat 25 1 Cat 35 2 Cat 45, 'Dog': Animal Max Speed 3 Dog 55 4 Dog 65 5 Dog 75} -------------------------------------------------- <class 'pandas.core.frame.DataFrame'>

convert groupby result to dictionary of dataframes

We first used the tuple class to convert the groupby() result to a tuple.

main.py
import pandas as pd df = pd.DataFrame({ 'Animal': ['Cat', 'Cat', 'Cat', 'Dog', 'Dog', 'Dog'], 'Max Speed': [25, 35, 45, 55, 65, 75] }) # (('Cat', Animal Max Speed # 0 Cat 25 # 1 Cat 35 # 2 Cat 45), ('Dog', Animal Max Speed # 3 Dog 55 # 4 Dog 65 # 5 Dog 75)) print(tuple(df.groupby('Animal')))
The code for this article is available on GitHub

The last step is to convert the tuple of tuples to a dictionary using the dict() class.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.