How to create a dictionary of data frames in Python

Overview

In this Answer, we will learn how to make a dictionary consisting of different data frames in Python. Usually, we can use this when we have a large number of datasets and want to access them easily in less time.

Example

In the example code below, we have two datasets that contain different data. We save these datasets in a list. To save data in the dictionary, we create a dictionary object named frames.

We use the enumerate() function to get both the index and contents of the list. The content is saved against the key of the dictionary which we get by an index value.

# import the pandas library to make the data frame
import pandas as pd
df1 = pd.DataFrame({
"Name": ["Shahroz", "Samad", "Usama"],
"Age": [22, 35, 58]
})
df2 = pd.DataFrame({
"Class": ["Chemistry","Physics","Biology"],
"Students": [30, 35, 40]
})
# list of data frames
dataframes = [df1, df2]
# dictionary to save data frames
frames={}
for key, value in enumerate(dataframes):
frames[key] = value # assigning data frame from list to key in dictionary
print("key: ", key)
print(frames[key], "\n")
# access to one data frame by key
print("Accessing the dataframe against key 0 \n", end ="")
print(frames[0])
# access to only column of specific data frame through dictionary
print("\nAccessing the first column of dataframe against key 1\n", end ="")
print(frames[1]["Class"])

Explanation

  • Line 2: We import the pandas library first to handle the data frames.
  • Lines 4–15: We make two data frames from the pandas function pd.Dataframe(), and save them in a list named dataframes.
  • Lines 18–20: After making an empty dictionary named frames, we iterate through the dataframes list to get its contents. In our case, the contents are are df1 and df2. We also get the index value of the list that we consider as a key value for the dictionary.
  • Line 21: We assign the contents of the list to the key of the frames dictionary, one by one, through iteration. We also print the key and assign data to the key in the dictionary as frames[key].
  • Lines 26–27: To explain the access to data better, we print the content against key 0 as frames[0].
  • Lines 30–31: We can also access the data frame content directly through the dictionary. For example, if we only want to get the first column "Class" of the dataset that is saved against key 1, we can use frames[1]["class"] to access that content. We can use this method to save multiple datasets against different keys in the dictionary. We can later access them by just defining the key.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved