keep highest value of duplicate keys in dicts

后端 未结 4 1189
名媛妹妹
名媛妹妹 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 19:45

    Here is my generalized solution to your question. It's a function that can combine an arbitrary number of dictionaries and has an option for other comparison functions should you want to say, keep track of the minimum values instead.

    import collections
    
    def combine_dicts(func, *dicts):
        default = collections.defaultdict(set)
        for d in dicts:
            for k, v in d.items():
                default[k].add(v)
        return {k: func(v) for k, v in default.items()}
    

    It uses a defaultdict with set as its default_factory to keep track of repetitions of keys with different values. Then it returns a dictionary comprehension to filter out the desired values.

    dict1 = {"a": 6, "b": 4, "c": 2, "g": 1}
    dict2 = {"a": 3, "d": 2, "f": 4, "g": 5}
    dict_comb = combine_dicts(max, dict1, dict2)
    print(dict_comb)  # -> {'a': 6, 'b': 4, 'c': 2, 'd': 2, 'f': 4, 'g': 5}
    

提交回复
热议问题