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 frameimport pandas as pddf1 = pd.DataFrame({"Name": ["Shahroz", "Samad", "Usama"],"Age": [22, 35, 58]})df2 = pd.DataFrame({"Class": ["Chemistry","Physics","Biology"],"Students": [30, 35, 40]})# list of data framesdataframes = [df1, df2]# dictionary to save data framesframes={}for key, value in enumerate(dataframes):frames[key] = value # assigning data frame from list to key in dictionaryprint("key: ", key)print(frames[key], "\n")# access to one data frame by keyprint("Accessing the dataframe against key 0 \n", end ="")print(frames[0])# access to only column of specific data frame through dictionaryprint("\nAccessing the first column of dataframe against key 1\n", end ="")print(frames[1]["Class"])
Explanation
- Line 2: We import the
pandaslibrary first to handle the data frames. - Lines 4–15: We make two data frames from the
pandasfunctionpd.Dataframe(), and save them in a list nameddataframes. - Lines 18–20: After making an empty dictionary named
frames, we iterate through thedataframeslist to get its contents. In our case, the contents are aredf1anddf2. We also get the index value of the list that we consider as akeyvalue for the dictionary. - Line 21: We assign the contents of the list to the
keyof theframesdictionary, one by one, through iteration. We also print thekeyand assign data to thekeyin the dictionary asframes[key]. - Lines 26–27: To explain the access to data better, we print the content against
key 0asframes[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 againstkey 1, we can useframes[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 ©2026 Educative, Inc. All rights reserved