keep highest value of duplicate keys in dicts

后端 未结 4 1187
名媛妹妹
名媛妹妹 2020-12-19 19:13

For school i am writing a small program for a rankinglist for a game. I am using dicts for this, with the name of the player as keyname, and the score as keyvalue. there wil

4条回答
  •  心在旅途
    2020-12-19 20:11

    Here's a variation on Matt Eding's answer that compares each value individually instead of creating sets of values. As a plus, it doesn't need any imports.

    def combine_dicts(func, *dicts):
        d0 = {}
        for d in dicts:
            for k, v in d.items():
                if k not in d0:
                    d0[k] = v
                else:
                    d0[k] = func(v, d0[k])
        return d0
    

提交回复
热议问题