Merge dictionary with dictionary map, and combine values

Is there a nice way of updating a dictionary using a dictionary map, and combine their values?

For example:

input = {"Puppy": 1, "Woof": 3, "Meow": 4, "Kitten": 6}

simplified_dict_map = {
    "Puppy" : "Dogs",
    "Woof" : "Dogs",
    "Meow" : "Cats",
    "Kitten" : "Cats",
}

Expected output:

result = {"Dogs": 4, "Cats": 10}

5 answers

  • answered 2021-04-21 14:13 JonSG

    A defaultdict goes a long say to simplifying this:

    import collections
    import json
    
    data_in = {"Puppy": 1, "Woof": 3, "Meow": 4, "Kitten": 6}
    simplified_dict_map = {"Puppy" : "Dogs", "Woof" : "Dogs", "Meow" : "Cats", "Kitten" : "Cats"}
    
    results = collections.defaultdict(int)
    for key, value in data_in.items():
        results[simplified_dict_map[key]] += value
    
    print(json.dumps(results, indent=2))
    

    Should give you:

    {
      "Dogs": 4,
      "Cats": 10
    }
    

  • answered 2021-04-21 14:13 megargayu

    Just use a for loop!

    result = {}
    for key, value in simplified_dict_map.items():
        if key in input:
            if value not in result:
                result[value] = 0
            result[value] += input[key]
    
    print(result) # {'Dogs': 4, 'Cats': 10}
    

  • answered 2021-04-21 14:15 a_guest

    You can use collections.defaultdict:

    from collections import defaultdict
    
    result = defaultdict(int)
    for key, value in input.items():
        result[simplified_dict_map[key]] += value
    

  • answered 2021-04-21 14:19 ah_onaly

    Something like this should work :

    keys = list(input.keys())
    result = {}
    for k in keys:
      if simplified_dict_map[k] in list(result.keys()):
        result[simplified_dict_map[k]]+=input[k]
      else:
        result[simplified_dict_map[k]]=input[k]
    

  • answered 2021-04-21 14:19 Anmol Parida

    solution = {}
    
    for k1, v1 in input_dict.items():
        for k2, v2, in simplified_dict_map.items():
            if k1 == k2:
                if v2 in solution.keys():
                    solution[v2] = solution[v2] + v1
                else:
                    solution[v2] = v1
    print(solution)