Sriramgirish
Sriramgirish

Reputation: 11

How to convert DF to Dictionary

Here is mycode:

import pandas as pd
import xlrd

p=pd.read_excel("D:\contacts.xlsx")
pp=p.set_index('Col-A').T
print(pp)
dic=pp.to_dict()

print(dic) 

My DF :

    Col-A  Col-B
0      1     10
1      2     20
2      3     30
3      4     40
4      5     50
5      6     60
6      7     70
7      8     80
8      9     90
9     10    100

Expected output : {1:10,2:20,3:30,4:40,5:50}

My output looks like:

Col-A  1   2   3   4   5 
Col-B  10  20  30  40  50  
{1: {'Col-B': 10}, 2: {'Col-B': 20}, 3: {'Col-B': 30}, 4: {'Col-B': 40}, 5: {'Col-B': 50}}

How can i achieve the expected output?

Upvotes: 0

Views: 62

Answers (2)

Wallace Coelho
Wallace Coelho

Reputation: 1

The to_dict method receives a parameter "orient" and the default value is dict.

You can transform this output setting the orient to "list".

df.to_dict('list')

You can iterate after this to flat your list into single value.

https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.to_dict.html

Upvotes: 0

It_is_Chris
It_is_Chris

Reputation: 14083

First set_index and then do to_dict and call Col-B

df.set_index('Col-A').to_dict()['Col-B']

# {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90, 10: 100}

Upvotes: 2

Related Questions