python;字典嵌套:像循环字典内字典的值,并根据内部字典相同的key,把values相加;可能说的有点模糊 ,直接上代码和图:
这是代码:
all_guests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'applse': 2, 'han sandwiches': 3},
'Carol': {'cups': 3, 'apples pie': 1}}
def total_brought(guests,item):
num_brought = 0
for k, v in guests.items():
num_brought = num_brought + v.get(item,0)
return num_brought
print('带的东西数量:')
for k, v in all_guests.items():
# print(k)
# print(v)
for k1, v1 in v.items():
print(k1 + '----:' + str(total_brought(all_guests, k1)))
图片;
我希望结果是apples可以相互合并:aplles的数量为7,而不是打印两个apples
谢谢大家!!