Skip to main content

How to convert a dictionary to a dictionary of data frames in Python

How to convert a dictionary to a dictionary of data frames in Python.

Here is a step-by-step tutorial on how to convert a dictionary to a dictionary of data frames in Python.

Step 1: Import the necessary libraries

import pandas as pd

Step 2: Create a dictionary with data

data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Tokyo']
}

Step 3: Convert the dictionary to a dictionary of data frames

data_frames = {key: pd.DataFrame(value) for key, value in data.items()}

Explanation: In this step, we use a dictionary comprehension to iterate over the key-value pairs in the original dictionary. For each key-value pair, we create a data frame using the pd.DataFrame() function from the Pandas library. Finally, we assign the data frame to a new key in the dictionary of data frames.

Step 4: Access the individual data frames

# Access the data frame with key 'Name'
name_df = data_frames['Name']

# Access the data frame with key 'Age'
age_df = data_frames['Age']

# Access the data frame with key 'City'
city_df = data_frames['City']

Explanation: In this step, we access the individual data frames from the dictionary of data frames using their respective keys.

Here is the complete code:

import pandas as pd

data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Tokyo']
}

data_frames = {key: pd.DataFrame(value) for key, value in data.items()}

name_df = data_frames['Name']
age_df = data_frames['Age']
city_df = data_frames['City']

That's it! You have successfully converted a dictionary to a dictionary of data frames in Python. Now you can access and manipulate each data frame individually.