0

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.

Timus
  • 10,974
  • 5
  • 14
  • 28
f444ran
  • 15
  • 1
  • 6
  • what is the actual output vs expected? – Seth Apr 13 '22 at 01:22
  • you already using dataframe which is complex enough to handle what ever your scenario is. you probably don't need a dictionary of pandas data frames. you may want to ask a better question with your original problem you are trying to solve. – eshirvana Apr 13 '22 at 01:28

1 Answers1

0

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 
scr
  • 853
  • 1
  • 2
  • 14