1

I have the following dataframe:

    ABC ID
0   4   M01
1   3   M02
2   5   M03

When i am using df.set_index(['ID']).to_dict() this gives me

{'ABC':{'M01':4,'M02':3,'M03':5}}

Required output is

{'M01':4,'M02':3,'M03':5}
Itamar Mushkin
  • 2,692
  • 2
  • 14
  • 30
  • 2
    In the future, please do not post dataframe examples with pipes and dashes, but rather post the data as it is, or even as a short code snippet to generate the dataframe. To learn more, please visit: https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples – Itamar Mushkin Dec 31 '19 at 13:38

2 Answers2

1

In this case, you want to turn the series defined by df['ABC'] into a dict, not the entire DataFrame.
try: df.set_index(['ID'])['ABC'].to_dict(), it should result in the required output.

Itamar Mushkin
  • 2,692
  • 2
  • 14
  • 30
0

dict and zip

Sometimes for simple tasks like this, it's better to use straight Python and avoid the unnecessary creation of Pandas objects just to get a dictionary.

dict(zip(df['ID'], df['ABC']))

{'M01':4,'M02':3,'M03':5}
piRSquared
  • 265,629
  • 48
  • 427
  • 571