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?

0

2 Answers 2

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'}
Sign up to request clarification or add additional context in comments.

Comments

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'}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.