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

后端 未结 5 742
爱一瞬间的悲伤
爱一瞬间的悲伤 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:08

    I would suggest using Willem Van Onsem answer, but if you don't want to import then here is an alternative.

    data = {
        'match1': {
            'player1': 57,
            'player2': 38},
        'match2': {
            'player3': 9,
            'player1': 42},
        'match3': {
            'player2': 41,
            'player4': 63,
            'player3': 91}
        }
    
    
    def orangecap(data):
        totals = {}
        for d in data.values():
            for k, v in d.items():
                totals[k] = totals.setdefault(k, 0) + v
    
        return max(totals.items(), key = lambda t:t[1])
    
    >>> orangecap(data)
    ('player3', 100)
    

提交回复
热议问题