Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dictionary from a CSV with two columns as the key in Python [duplicate]

I am trying to create a dictionary from a CSV with 3 columns where the first two columns become the key and the third column becomes the value:

In this example, example.csv contains:

Column-1    Column-2   Column-3
1           A          foo
2           B          bar

The expected output should be:

dictionary = {1, A: foo, 2, B: bar}

I am currently attempting to import from a pandas dataframe and convert to a dictionary. I am using the following unsuccessfully:

df = pd.read_csv("example.csv")
dictionary = df.set_index(['Column-1', 'Column-2']).to_dict()

Is there a way to do this using pandas to create the dictionary or is there a more elegant way to convert the csv to a dictionary?

like image 621
notlaughing Avatar asked Oct 17 '25 13:10

notlaughing


1 Answers

IIUC you are close - need select column by ['Column-3']:

d = df.set_index(['Column-1', 'Column-2'])['Column-3'].to_dict()
print (d)
{(2, 'B'): 'bar', (1, 'A'): 'foo'}
like image 139
jezrael Avatar answered Oct 20 '25 03:10

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!