Pandas Dataframe to Tuple Dictionary

Question:

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!

Asked By: Tess

||

Answers:

After getting the result from pandas.DataFrame.to_dict() you can iterate over dict and create tuple_dict like the below:

dct = df.to_dict()
print(dct)
# {
#     'Period 1': {'Customer 1': 31, 'Customer 2': 46}, 
#     'Period 2': {'Customer 1': 222, 'Customer 2': 187}
# }

res = {(k2, k1) : v2 for k1,v1 in dct.items() for k2,v2 in v1.items()}
print(res)

Output:

{('Customer 1', 'Period 1'): 31,
 ('Customer 2', 'Period 1'): 46,
 ('Customer 1', 'Period 2'): 222,
 ('Customer 2', 'Period 2'): 187}
Answered By: I'mahdi

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,
}
Answered By: Andrej Kesely