Pandas, read csv file into dictionary

Viewed 74

Is there a way in which it is possible to read a CSV file in a dictionary such that custom rows together in a tuple are the key and the rest (in a tuple) is the value?

Here is an example table:

A |B |C |D |E
--------------
0 |0 |0 |5 |1
0 |1 |0 |2 |8
1 |0 |0 |5 |7
1 |1 |0 |3 |7
0 |0 |1 |9 |0

The result:

dictionary[(A,B,C)] = (D, E)
print(dictionary[(0,0,0)]) # (5,1)

Is there an efficient way to achieve that?

2 Answers

Considering the pandas dataframe df:

 A  B  C  D  E
 0  0  0  5  1
 0  1  0  2  8
 1  0  0  5  7
 1  1  0  3  7
 0  0  1  9  0

Let's zip the columns A, B, C and D, E together and make the key value pair of tuples inside dict comprehension:

k, v = ['A', 'B', 'C'], ['D', 'E']
dct = {tuple(x): tuple(y) for x, y in zip(df[k].to_numpy(), df[v].to_numpy())}

Result:

{(0, 0, 0): (5, 1),
 (0, 1, 0): (2, 8),
 (1, 0, 0): (5, 7),
 (1, 1, 0): (3, 7),
 (0, 0, 1): (9, 0)}

I am not sure if this is the best solution, but it works:

pd.concat([df[['A', 'B', 'C']].apply(tuple, 1),
           df[['D', 'E']].apply(tuple, 1)], axis=1)\
  .set_index(0)[1].to_dict()
#{(0, 0, 0): (5, 1), (0, 1, 0): (2, 8), (1, 0, 0): (5, 7), 
# (1, 1, 0): (3, 7), (0, 0, 1): (9, 0)}
Related