Home > other >  Acess a dataframe in dictionaries
Acess a dataframe in dictionaries

Time:12-13

Morning,

I have a dictionary that contains pairs of 1 keys and 2 values, at those values are dataframes

dictionary = {'key_1' : [df_1, df_2],
             'key_2' : [df_3, df_4], ....}

I want to create a new data frame (named using the key) that merges the two values of each key

new_df_key = pd.merge(left = df_1,
                      right = df_2,
                      how = 'left',
                      on = 'column_name')

I having trouble retrieving the name of the data frames to do the merge. The goal is to iterate through the keys and values in the dictionary and create new data frames. Any ideas?

Thanks!

CodePudding user response:

Not certain I'm understanding the question correctly, but I think you may want to do something like this.

merged_df_list = []
for key in dictionary.keys():
    df1, df2 = dictionary[key][0], dictionary[key][1]
    key = pd.merge(left = df1, right = df2, how = "left", on = "column_name")
    merged_df_list.append(key)

This should give you a list of merged dataframes named by the keys in the dictionary

Edit:

Created using dictionary instead so can access the merged_dfs by the key name:

merged_df_dict = {}
for key in dictionary.keys():
    df1, df2 = dictionary[key][0], dictionary[key][1]
    merged_df = pd.merge(left = df1, right = df2, how = "left", on = "column_name")
    merged_df_dict[key] = merged_df

This should allow you to access the new df by the keyname by:

merged_df_dict[keyname] # Returns the new df merged by that key
  • Related