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

时间:2019-04-12 02:34:58

标签: python dictionary

我正在练习一些编码,以学习如何在多个嵌套字典中添加具有值的键列表。最终输出是在代码中产生“水果”总数。有没有一种方法可以不必将嵌套字典分解成多个单独的字典并使用集合中的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())

预期结果应为:

  

水果总数:64

     

非水果总数:58

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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())

答案 2 :(得分:0)

尝试一下:

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)