Creating a dictionary of dictionaries from groupby

Viewed 222

I have a dataframe that looks like this:

    Friend A        Friend B    Score
0    Walter          John        22
1    Walter          Jack        32
2    Fred            John        10
3    Caleb           Jack        5   

What I'd like to produce is this:

{"Walter": {"John": 22, "Jack": 32}, "Fred": {"John": 10}, "Caleb": {"Jack": 5}}

What I have so far is this:

x = Network.groupby("Friend A")[["Friend A", "Friend B", "Score"]]

I've tried doing the following:

x.apply(list).to_dict()

But this isn't the result I'd like to get. How can I achieve this result?

2 Answers
In [17]: df.groupby("Friend A").apply(lambda x: x.set_index("Friend B")['Score'].to_dict()).to_dict()

Out[17]:
{'Caleb': {'Jack': 5},
 'Fred': {'John': 10},
 'Walter': {'Jack': 32, 'John': 22}}
a = Network.groupby("Friend A").apply(lambda x: dict(zip(x["Friend B"], x["Score"]))).to_dict()
Related