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?
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With