5

I been trying this for the past hour but with little to no success

I was wondering how can I make this dataframe to a dictionary

DF

 Country      Continent 
 1            Europe
 2            Europe
 3            Asia
 4            Australia

Desired

  {'1': 'Europe',
  '2': 'Europe',
  '3': 'Asia',
  '5': 'Australia'}

I tired like x10 different variations of code similar to this but it didn't work

 df.set_index('Country', inplace=True)
 df = df.to_dict('dict')
OptimusPrime
  • 619
  • 8
  • 17
  • 1
    Duplicate of [python pandas dataframe to dictionary](https://stackoverflow.com/questions/18695605/python-pandas-dataframe-to-dictionary/18695700) – Zero Sep 18 '18 at 13:10
  • Possible duplicate of [python pandas dataframe to dictionary](https://stackoverflow.com/questions/18695605/python-pandas-dataframe-to-dictionary) – IanS Sep 18 '18 at 13:12

2 Answers2

7

You can select column Continent for Series and then use Series.to_dict:

>>> d = df.set_index('Country')['Continent'].to_dict()
>>> print(d)
{'Paris': 'Europe', 'Berlin': 'Europe', 'Macow': 'Asia', 'Melbourne': 'Australia'}
Jonas Adler
  • 10,365
  • 5
  • 46
  • 73
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
4

You can use the dict constructor with zip

dict(zip(df.Country, df.Continent))

{1: 'Europe', 2: 'Europe', 3: 'Asia', 4: 'Australia'}
piRSquared
  • 285,575
  • 57
  • 475
  • 624