"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Pandas DataFrame to Dictionary: List Value Conversion Tips

Pandas DataFrame to Dictionary: List Value Conversion Tips

Posted on 2025-04-12
Browse:349

How to Convert a Pandas DataFrame to a Dictionary with List Values?

Convert a Pandas DataFrame to a Dictionary

In many data manipulation tasks, extracting data from a Pandas DataFrame into a convenient format is necessary. One common need is to convert a DataFrame to a Python dictionary, where the elements of the first column become keys and the elements of other columns in the same row become values.

Example

Consider the following DataFrame:

    ID   A   B   C
0   p    1   3   2
1   q    4   3   2
2   r    4   0   9

We want to convert this DataFrame to a dictionary of the following form:

{'p': [1,3,2], 'q': [4,3,2], 'r': [4,0,9]}

Solution

To achieve this, we can utilize the to_dict() method provided by Pandas. However, to align the DataFrame into the desired format, we need to set the 'ID' column as the index and transpose the DataFrame using .T. Additionally, we specify the orient argument in to_dict() to output a list of values for each column.

The following code demonstrates this approach:

df.set_index('ID').T.to_dict('list')

This will produce the desired dictionary:

{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}

Alternative Options

Beyond the default dict format, Pandas offers a range of options for outputting dictionaries using the orient argument:

  • dict: Column names as keys, values as dictionaries of index:data pairs
  • list: Keys are column names, values are lists of column data
  • series: Similar to 'list', but values are Series objects
  • split: Column names as keys, data values as values, and index labels as a separate key
  • records: Each row becomes a dictionary with column names as keys and data as values
  • index: Similar to 'records', but a dictionary of dictionaries with index labels as keys
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3