How to operate on nested dictionary in python 3.x?

后端 未结 5 698
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-29 14:47

I am stuck with this question, can you solve the challenge? Here we go!

We represent scores of players across a sequence of matches in a two level dictionary as follows:

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-29 15:19

    with pandas it's really easy:

    In [78]: d
    Out[78]: 
    {'match1': {'player1': 57, 'player2': 38},
     'match2': {'player1': 42, 'player3': 9},
     'match3': {'player2': 41, 'player3': 91, 'player4': 63}}
    
    In [79]: pd.DataFrame(d).sum(axis=1).idxmax()
    Out[79]: 'player3'
    
    In [80]: pd.DataFrame(d).sum(axis=1).max()
    Out[80]: 100.0
    

    First convert it to a DataFrame, then sum over the columns, and find the max :)

提交回复
热议问题