[英]How to add values across multiple nested dictionary in python?
I'm practicing some coding to learn how to add up a list of keys with values in multiple nested dictionaries.我正在练习一些编码,以学习如何将具有多个嵌套字典中的值的键列表相加。 The final output is to produce a total count of "fruits" in the code.最终输出是生成代码中“水果”的总数。 Is there a way to do so without having to break up the nested dictionaries into multiple separate dictionaries and use Counter from collections?有没有办法做到这一点,而不必将嵌套字典分解成多个单独的字典并从集合中使用 Counter?
fruit_count = 0
not_fruit_count = 0
basket_items = {1: {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8},
2: {'pears': 5, 'grapes': 19, 'kites': 3, 'sandwiches': 8, 'bananas': 4},
3: {'peaches': 5, 'lettuce': 2, 'kites': 3, 'sandwiches': 8, 'pears': 4},
4: {'lettuce': 2, 'kites': 3, 'sandwiches': 8, 'pears': 4, 'bears': 10}}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
for item, value in combined.items():
if item in fruits:
fruit_count += value
else:
not_fruit_count += value
print("\nTotal fruit count: {}".format(fruit_count).title())
print("\nTotal non-fruit count: {}".format(not_fruit_count).title())
The expected result should give:预期的结果应该是:
Total fruit count: 64水果总数:64
Total non-fruit count: 58非水果总数:58
for item, value in basket_items.items():
for k, v in value.items():
if k in fruits:
fruit_count += v
else:
not_fruit_count += v
Total Fruit Count: 64, Total Non-Fruit Count: 58水果总数:64,非水果总数:58
fruit_count = sum(sum(basket.get(fruit, 0)
for basket in basket_items.values())
for fruit in fruits)
# OR
fruit_count = sum(sum(val
for key, val in basket.items()
if key in fruits)
for basket in basket_items.values())
non_fruit_count = sum(sum(val
for key, val in basket.items()
if key not in fruits)
for basket in basket_items.values())
Try this:尝试这个:
for key, value in basket_items.items()
if key in fruits:
fruit_count += value
else:
not_fruit_count += value
print(fruit_count, not_fruit_count)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.