【问题标题】:How to add values across multiple nested dictionary in python?如何在python中的多个嵌套字典中添加值?
【发布时间】:2019-04-12 02:34:58
【问题描述】:

我正在练习一些编码,以了解如何在多个嵌套字典中将键列表与值相加。最终输出是在代码中产生“水果”的总数。有没有办法做到这一点,而不必将嵌套字典分解为多个单独的字典并使用集合中的 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

【问题讨论】:

  • 您的代码中在哪里定义了combined,它的值是多少?
  • for _, combined in basket_items.iteritems():\n for item, value in combined.iteritems() ?

标签: python dictionary


【解决方案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

【讨论】:

    【解决方案2】:
    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())
    

    【讨论】:

      【解决方案3】:

      试试这个:

      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)
      

      【讨论】:

        猜你喜欢
        • 2022-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-25
        • 1970-01-01
        • 2018-11-07
        • 2016-12-10
        • 2018-01-29
        相关资源
        最近更新 更多