[英]Summing specific elements in nested dict
I have got 3 different bags that I represent using a nested dictionary. 我有3个使用嵌套字典表示的袋子。 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. 它们的键是“ bag1”,“ bag2”和“ bag3”,并且依次包含不同数量的不同颜色的球,每种颜色类别也由字典表示。 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}}
. 例如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}
. 现在,我想以另一种形式的最终字典结束: 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. 在递归函数get_value
下面,它将从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}
输出: {'red': 5, 'blue': 9, 'green': 15}
Using list comprehensions
to solve this - 使用list comprehensions
来解决此问题-
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.