JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Convert Pandas DataFrame to Dictionary

Author:JIYIK Last Updated:2025/05/01 Views:

This tutorial will show you how to convert a Pandas DataFrame into a dictionary with the index column elements as keys and the corresponding elements of other columns as values. We will use the following DataFrame in the article.

import pandas as pd

df = pd.DataFrame(
    [["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
    columns=["Name", "Age", "Course"],
)

print(df)

Output:

   Name  Age Course
0   Jay   16    BBA
1  Jack   19  BTech
2  Mark   18    BSc

to_dict()Convert a Pandas DataFrame to a dictionary using the

The Pandas to_dict()function converts a DataFrame to a dictionary. The parameters determine the format of the dictionary and how the key-value pairs are associated. Below is a to_dict()basic example of using convertDataFrame to Dictionary.

import pandas as pd

df = pd.DataFrame(
    [["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
    columns=["Name", "Age", "Course"],
)

d1 = df.to_dict()
print(d1)

Output:

{'Name': {0: 'Jay', 1: 'Jack', 2: 'Mark'}, 'Age': {0: 16, 1: 19, 2: 18}, 'Course': {0: 'BBA', 1: 'BTech', 2: 'BSc'}}

As you can see in the output, the column names are converted to keys, each record as value and the index as their key.


Pandas DataFrame Methods for Converting Dictionaries

We can change the format of the final dictionary by passing arguments list, records, series, index, splitand . For example, when we pass and as arguments, we get the column names as keys, but the value pairs are converted to lists and series rows, respectively. The following example will demonstrate this.dictlistseries

import pandas as pd

df = pd.DataFrame(
    [["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
    columns=["Name", "Age", "Course"],
)

d_list = df.to_dict("list")
print(d_list)

d_series = df.to_dict("series")
print(d_series)

Output:

{'Name': ['Jay', 'Jack', 'Mark'], 'Age': [16, 19, 18], 'Course': ['BBA', 'BTech', 'BSc']}

{'Name': 0     Jay
1    Jack
2    Mark
Name: Name, dtype: object, 'Age': 0    16
1    19
2    18
Name: Age, dtype: int64, 'Course': 0      BBA
1    BTech
2      BSc
Name: Course, dtype: object}

Pandas DataFrame to List of Dictionaries

We can also pass each line as a separate dictionary to the function records. The final result is a list with each line as a dictionary. For example:

import pandas as pd

df = pd.DataFrame(
    [["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
    columns=["Name", "Age", "Course"],
)

d_records = df.to_dict("records")
print(d_records)

Output:

[{'Name': 'Jay', 'Age': 16, 'Course': 'BBA'}, {'Name': 'Jack', 'Age': 19, 'Course': 'BTech'}, {'Name': 'Mark', 'Age': 18, 'Course': 'BSc'}]

Pandas DataFrame to Dictionary by Row

But in many cases, we may not want the column names as dictionary keys. For such cases, we can pass indexDataFrame index as key. The following code snippet demonstrates this.

import pandas as pd

df = pd.DataFrame(
    [["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
    columns=["Name", "Age", "Course"],
)

d_index = df.to_dict("index")
print(d_index)

Output:

{0: {'Name': 'Jay', 'Age': 16, 'Course': 'BBA'}, 1: {'Name': 'Jack', 'Age': 19, 'Course': 'BTech'}, 2: {'Name': 'Mark', 'Age': 18, 'Course': 'BSc'}}

Dataframe converted to a dictionary with one column as key

But what if we prefer to use the elements of one column as keys and the elements of other columns as values? This can be achieved by simply taking the desired column as the index of the DataFrame and .T()transposing it using the function.

example:

import pandas as pd

df = pd.DataFrame(
    [["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
    columns=["Name", "Age", "Course"],
)

d_names = df.set_index("Name").T.to_dict("list")
print(d_names)

Output:

{'Jay': [16, 'BBA'], 'Jack': [19, 'BTech'], 'Mark': [18, 'BSc']}

Convert a Pandas DataFrame to a dictionary using the dict()and functionszip()

Python dict()functions can also convert Pandas DataFrame to dictionary. We should also use zip()the function, passing each column as its argument to create a parallel iterator. Then zip()the function will yield all the values ​​of a row in each iteration.

import pandas as pd

df = pd.DataFrame(
    [["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
    columns=["Name", "Age", "Course"],
)

d = dict([(i, [a, b]) for i, a, b in zip(df["Name"], df["Age"], df["Course"])])
print(d)

Output:

{'Jay': [16, 'BBA'], 'Jack': [19, 'BTech'], 'Mark': [18, 'BSc']}

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

将 Pandas DataFrame 写入 CSV

Publish Date:2024/04/21 Views:189 Category:Python

本教程介绍了我们如何使用 pandas.DataFrame.to_csv()函数将 DataFrame 写入 CSV 文件。

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial