简体   繁体   中英

Summing specific elements in nested dict

I have got 3 different bags that I represent using a nested dictionary. Their keys are 'bag1', 'bag2' and 'bag3' and, in turn, they contain different coloured balls of different quantities, each colour category also represented by a dictionary. How do end up with a dictionary that simply adds all the respective colours in each bag? For example, dict1 = {'bag1': { 'red' : 2, 'blue' : 5, 'green' : 7}, 'bag2' : { 'red' : 3, 'blue': 4, 'green': 8}} . Now, I want to end up with another, final dictionary of the form: dict2 = { 'red' : 5, 'blue': 9, 'green': 15} . Could someone please provide me with a function to do this?

First you want to create result dictionary:

dict2 = {}
for key in dict1['bag1'].keys():
    dict2[key] = 0

then fill it

for bag in dict1.values():
    for key, value in bag.items():
        dict2[key] += value

You can use Counter from collections module:

from collections import Counter
dict1 = {'bag1': {'red': 2, 'blue': 5, 'green': 7}, 'bag2': {'red': 3, 'blue': 4, 'green': 8}}

counter = sum(map(Counter, dict1.values()), Counter())
print dict(counter)

Output

{'blue': 9, 'green': 15, 'red': 5}

Below recursive function get_value will find the value of keys from JSON.

import json

def get_value(key, mydict):
    if key in mydict:
        return mydict[key]

    if type(mydict) is dict:
        for i in mydict:
            if type(i) is dict:
                return get_value(key, i)
    return 0

def get_sum(dict1, dict2):
    red, blue, green = 0, 0, 0
    red = get_value('red', dict1) + get_value('red', dict2)
    blue = get_value('blue', dict1) + get_value('blue', dict2)
    green = get_value('green', dict1) + get_value('green', dict2)
    return {
        'red':red,
        'blue': blue,
        'green':green
    }

if __name__=="__main__":
    dict1 = {'bag1': { 'red' : 2, 'blue' : 5, 'green' : 7}, 'bag2' : { 'red' : 3, 'blue': 4, 'green': 8}}
    dict2 = { 'red' : 5, 'blue': 9, 'green': 15}
    final_sum = get_sum(dict1, dict2)
    print(final_sum)

output: {'red': 5, 'blue': 9, 'green': 15}

Using list comprehensions to solve this -

a=[ d.items() for d in list(dict1.values())]
my_tuples=[item for sublist in a for item in sublist]
my_set = {x[0] for x in my_tuples}
my_sums = dict([(i,sum(x[1] for x in my_tuples if x[0] == i)) for i in my_set])
print(my_sums)
    {'green': 15, 'red': 5, 'blue': 9}

输出屏幕截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM