pythonpandasdataframedictionarynested

Create nested dictionary from a pandas dataframe


I have this table:

Team X or Y Percentage
A X 80%
A Y 20%
B X 70%
B Y 30%
C X 60%
C Y 40%

I want to create a nested dictionary out of this so that if I input the team name and input X or Y, I get the percentage as a return value.

In Python I used the .tolist() method to create lists out of each individual column.

My initial strategy was to create a dict out of the second two columns dict_1 = dict(zip(list2, list3)) and then dict_2 = dict(zip(list1, dict_1)) but that didn't work out because column "X or Y", for example, has similar values, and dictionary keys cannot have repeated values.

The output I had in mind was

{'A':{'X':80%, 'Y':20%}, 'B':{'X':70%,'Y':30%}, ...}

How would I create this? Is there a better way to do this?


Solution

  • Use pd.DataFrame.pivot:

    >>> df.pivot(columns='Team', index='X or Y', values='Percentage').to_dict()
    {'A': {'X': '80%', 'Y': '20%'}, 'B': {'X': '70%', 'Y': '30%'}, 'C': {'X': '60%', 'Y': '40%'}}