简体   繁体   中英

python: From dict to df and back to dict again

Suppose we have this dict

d = {'A':True, 'B':False, 'C':True}

With this command, I get this desired Dataframe:

import pandas as pd
df = pd.DataFrame(d.items())

   0      1
0  A   True
1  B  False
2  C   True

But when I want to transform back to a dict, I get this:

d_again = df.to_dict('records')

[{0: 'A', 1: True}, {0: 'B', 1: False}, {0: 'C', 1: True}]

Which its not the same as the first dict d.

Thank you for your help: :)

You can use values attribute of the dataframe and pass it to dict

d_again = dict(df.values)
{'A': True, 'B': False, 'C': True}

The direct translation would be

print(df.set_index(0)[1].to_dict())

Which yields

{'A': True, 'B': False, 'C': True}

Full code:

import pandas as pd

dct_in = {'A':True, 'B':False, 'C':True}
df = pd.DataFrame(dct_in.items())
dct_out = df.set_index(0)[1].to_dict()
assert dct_in == dct_out

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM