3

I have a pandas DataFrame with 2 columns. How can I convert this into a Python dictionary with id as key and name as value?

INPUT

id | name
1  | hello
2  | world

REQUIRED OUTPUT

{
    "1": "hello",
    "2": "world",
}
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
konichiwa
  • 532
  • 1
  • 5
  • 23
  • Does this answer your question? [dataframe to dict such that one column is the key and the other is the value](https://stackoverflow.com/questions/53941224/dataframe-to-dict-such-that-one-column-is-the-key-and-the-other-is-the-value) – Mayank Porwal May 20 '20 at 21:27

5 Answers5

4

You can just do this:

In [1256]: df.set_index('id').to_dict()['name']
Out[1256]: {1: 'hello', 2: 'world'}
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
2

zip the two columns you want.

dict(zip(df['id'].astype(str), df['name']))
#{'1': 'hello', '2': 'world'}

If you want to use the pandas methods, make things strings then set the keys to your index and grab the column you want to be the values and go with .to_dict

(df.astype('str')
   .set_index('id')['name']
   .to_dict()
)
ALollz
  • 57,915
  • 7
  • 66
  • 89
1

Please try:

dict_ = {}
for  i , value in enumerate(df[‘name’]):
    dict_[i] = value

You can also try:

dict_ = df.set_index('id').to_dict()['name']

If you want dictionary value as list:

dict_ = df.set_index('id').T.to_dict('list')
Kriti Pawar
  • 832
  • 7
  • 15
1

Let us do

d=dict(zip(df.id,df.name))
BENY
  • 317,841
  • 20
  • 164
  • 234
1

Other answers focus on the conversion from pandas DataFrame to dict, however the question is also about having the index values as strings.

The solution for that is to map the index to str beforehand :

df.to_dict()
{'name': {0: 'hello', 1: 'world'}}

df.index = df.index.map(str)
df.to_dict()
{'name': {'0': 'hello', '1': 'world'}}
Skippy le Grand Gourou
  • 6,976
  • 4
  • 60
  • 76