+1 vote
in Programming Languages by (7k points)

My DataFrame has two columns. I want to convert it to a dictionary in which the elements of the first column will be keys and the elements of the second column will be values. By using to_dict() function, I am not getting the desired result. 

Here is an example:

E.g.

>>> df

  c1  c2

0  a  11

1  b  12

2  c  13

to

{'a':11', 'b':12, 'c':13}

1 Answer

0 votes
by (13.5k points)
edited by

When you use to_dict() function, it creates a dictionary with columns as keys and the values contain another dictionary having rows as keys and the cell element corresponding to rows and columns as values.

E.g.

>>> import pandas as pd
>>> df =pd.DataFrame({'c1':['a','b','c'], 'c2':[11,12,13]})
>>> df
  c1  c2
0  a  11
1  b  12
2  c  13
>>> df.to_dict()
{'c1': {0: 'a', 1: 'b', 2: 'c'}, 'c2': {0: 11, 1: 12, 2: 13}}

So, to get your desired dictionary, you need to make some changes in the dataframe before applying to_dict() function.

Here are two approaches you can try to get your desired result:

Approach 1:

>>> df.set_index('c1').to_dict()
{'c2': {'a': 11, 'b': 12, 'c': 13}}
>>> df.set_index('c1').to_dict().values()
dict_values([{'a': 11, 'b': 12, 'c': 13}])
>>> for i in df.set_index('c1').to_dict().values():
...     d=i
...
>>> d
{'a': 11, 'b': 12, 'c': 13}


Approach 2:

>>> df.set_index('c1').T.to_dict('records')
[{'a': 11, 'b': 12, 'c': 13}]
>>> df.set_index('c1').T.to_dict('records')[0]
{'a': 11, 'b': 12, 'c': 13}

to_dict() function supports the following orient to determines the type of the values of the dictionary.
orient : str {‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’}

...