Skip to content
Advertisement

How do I make a dataframe from two dictionaries based on matched keys

The idea is to make a pandas data frame with the following two dictionaries:

d1={('A','B'):{('C','D'),('E','F')},
    ('X','Z'):{('R','T')}}

d2={('A','B'):{('J','K')}}

The keys are IDs Desired data frame output based on the matching keys:

Matched ID  | Value d1  | Value d2
('A','B') | ('C','D') | ('J','K') 
('A','B') | ('E','F') | ('J','K') 

The ID (‘X’, ‘Z’) only exists in d1 but not d2 so it is not included in the desired output.

Advertisement

Answer

Try:

df1 = pd.DataFrame.from_dict(d1, orient='index').unstack().droplevel(0).rename('B')
df2 = pd.DataFrame.from_dict(d2, orient='index').unstack().droplevel(0).rename('C')

df = pd.merge(df1, df2, left_index=True, right_index=True, how='inner') 
       .rename_axis('A').reset_index()
print(df)

# Output
        A       B       C
0  (A, B)  (C, D)  (J, K)
1  (A, B)  (E, F)  (J, K)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement