Pandas Dataframe to Tuple Dictionary

I would like to create a tuple dictionary of a dataframe. Currently, I have a dataframe looking like this:


xxxxxxxxx | Period 1 | Period 2 |
Customer  | -------- | -------- |
Customer 1| 31       | 222      |
Customer 2| 46       | 187      |

I would like to get a tuple dictionary of this:

tuple_dict = 
{('Customer 1', 'Period 1'): 31,
 ('Customer 2', 'Period 1'): 46, 
 ('Customer 1', 'Period 2'): 222, 
 ('Customer 2', 'Period 2'): 187} 

It is probably posted somewhere already but I can’t find it unfortunately. Could somebody help me?

Currently I converted the above looking table to a dictionary with

dict = df.to_dict(): 

This created 4 seperate dictionaries (one for each period),

Period 1: {'Customer 1': 31, 'Customer 2': 46}
Period 2: {'Customer 1': 222 ,'Customer 2': 187}

But I really would like to have tuple dictionaries as described above. Thank you so much for helping!

>Solution :

Try:

print(df.stack().to_dict())

Prints:

{
    ("Customer 1", "Period 1"): 31,
    ("Customer 1", "Period 2"): 222,
    ("Customer 2", "Period 1"): 46,
    ("Customer 2", "Period 2"): 187,
}

Leave a Reply