Home > Enterprise >  Adding lists of dicts
Adding lists of dicts

Time:06-05

Using the following example:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a':[3],'b':['ABC-1|ABD-5'],'c':[2],'d':[1],'e':[1],'f':[8]})

In [3]: columns = ['b','f']

In [4]: df_dict = df[columns].to_dict(orient='records')

In [5]: df_dict
Out[5]: [{'b': 'ABC-1|ABD-5', 'f': 8}]

In [6]: df_dict2 = df[['c']].to_dict(orient='records')

In [7]: df_dict2
Out[8]: [{'c': 2}]

How do I combine df_dict and df_dict2 such that the end result is:

[{'b': 'ABC-1|ABD-5', 'f': 8, 'c':2}]

Given that they're lists, I tried df_dict.append(df_dict2) but it just gives:

[{'b': 'ABC-1|ABD-5', 'f': 8},[{'c': 2}]]

Any advice/suggestions/ideas?

CodePudding user response:

update the contents of the dictionary within df_dict with the contents of the dictionary in df_dict2

df_dict[0].update(df_dict2[0])
  • Related