4

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?

notlaughing
  • 177
  • 2
  • 12

2 Answers2

4

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'}
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2

Option 1

dict(zip(zip(df['Column-1'], df['Column-2']), df['Column-3']))

{(1, 'A'): 'foo', (2, 'B'): 'bar'}

Option 2

{(a, b): c for a, b, c in df.values}

{(1, 'A'): 'foo', (2, 'B'): 'bar'}
piRSquared
  • 285,575
  • 57
  • 475
  • 624