【发布时间】: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