Home > Mobile >  Merge dictionary containing dataframes
Merge dictionary containing dataframes

Time:04-14

I am merging multiple dictionaries which contains dataframe as values. I am following this as reference(How to merge multiple dicts with same key or different key?). However the values in merged dictionary comes as list and I would need it to be a dataframe.

df1 = pd.DataFrame([1,2,3])
df2 = pd.DataFrame([4,5,6])
df3 = pd.DataFrame([7,8,9])
d1 = {'a' : df1 , 'b' : df2}
d2 = {'c' : df3 , 'a' : df2}

dd = defaultdict(list)
for d in (d1, d2): # you can list as many input dicts as you want here
    for key, value in d.items():
        dd[key].append(value)

Expected Output:

{'a' : df1   df2 ,'b' : df2 , 'c': df3}

The keys need not be present in all dict. Using Python 3.

CodePudding user response:

I think this snippet is what you are looking for:

df1 = pd.DataFrame([1,2,3])
df2 = pd.DataFrame([4,5,6])
df3 = pd.DataFrame([7,8,9])
d1 = {'a' : df1 , 'b' : df2}
d2 = {'c' : df3 , 'a' : df2}

dd = {}
for d in (d1, d2): # you can list as many input dicts as you want here
    for key, value in d.items():
        if key in dd.keys():
            dd[key]  = value 
        else:
            dd[key] = value 
  • Related