如何在python中跨多个嵌套字典添加值?

如何在python中跨多个嵌套字典添加值?,python,dictionary,Python,Dictionary,我正在练习一些编码,以了解如何在多个嵌套字典中添加具有值的键列表。最后的输出是生成代码中的“果实”总数。有没有一种方法可以做到这一点,而不必将嵌套的字典拆分为多个单独的字典,并使用集合中的计数器 fruit_count = 0 not_fruit_count = 0 basket_items = {1: {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8}, 2: {'pears': 5, 'gr

我正在练习一些编码,以了解如何在多个嵌套字典中添加具有值的键列表。最后的输出是生成代码中的“果实”总数。有没有一种方法可以做到这一点,而不必将嵌套的字典拆分为多个单独的字典,并使用集合中的计数器

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())
预期结果应给出:

水果总数:64

非水果总计数:58

水果总数:64, 非水果总计数:58

试试这个:

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)

您的代码中定义了组合的
在哪里,其值是多少?
对于组合在篮子中的项目。iteritems():\n对于项目,组合在一起的.iteritems()中的值
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
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)