Home > Net >  How to concatenate 2 dict in Python with concat
How to concatenate 2 dict in Python with concat

Time:11-30

I have 2 dict objects with the same key but different elements.I would like to merge them into one dict.

First, I used append and it works but append is deprecated so that I prefer to use concat.

here is the code :

data1 = {'a':1, 'b':2}
data2 = {'a':3, 'b':4}

list = [data1, data2]
df = pd.DataFrame()

for x in range(len(list)):
    df = df.append(list[x], ignore_index=True)
    
df

The code below works with append. In my case I would like to have concat Maybe you can help. Thanks

CodePudding user response:

The following code works but may not be very efficient:

data1 = {'a':1, 'b':2}
data2 = {'a':3, 'b':4}

list = [data1, data2]
df = pd.concat([pd.DataFrame(list[i], index=[i]) for i in range(len(list))])

print(df)

CodePudding user response:

Here is a proposition using pandas.concat with pandas.DataFrame.unstack :

list_of_dicts = [data1, data2]

df= (
        pd.concat(dict(enumerate(map(pd.Series,
                                     list_of_dicts))))
            .unstack()
    )

# Output :

print(df)

   a  b
0  1  2
1  3  4

NB : Try to avoid naming your variables with python built-in function names (list, dict, ..)

  • Related