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.
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"])
pandas
library first to handle the data frames.pandas
function pd.Dataframe()
, and save them in a list named dataframes
.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.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]
.key 0
as frames[0]
."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