4 回答

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
我弄得有點(diǎn)亂,但是可以用
bought = {'Banana':2, 'Avocado':3, 'Cherries':1}
price_of = {'Apple': 6,
'Avocado': 5,
'Banana': 3,
'Blackberries': 10,
'Blueberries': 12,
'Cherries': 7,
'Pineapple': 7}
#Creating a new sorted dictionary named b
a = sorted(bought)
b = {}
for fruit in a:
b[fruit] = bought.get(fruit)
#Making bought be b
bought = b
def summary(items, price):
total = 0
for i in items:
print(f" {items.get(i)} {i} : {items.get(i)*price.get(i)}")
total = total + items.get(i)*price.get(i)
print(f" Total {total}")
summary(bought, price_of)
希望能幫助到你

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
bought = {'Banana':2, 'Avocado':3, 'Cherries':1}
price_of = {'Apple': 6,
'Avocado': 5,
'Banana': 3,
'Blackberries': 10,
'Blueberries': 12,
'Cherries': 7,
'Pineapple': 7}
# bought = sorted(bought)
def print_summary(items,fprice):
# items = counter_item(chart)
# for item, n in fprice.items():
# print(n, item, ':', n * items[item])
# print('total', sum(n * items[item]))
total = 0
for i, k in enumerate(sorted(items, key= lambda x: items[x], reverse=True )):
print(items[k], k, ':', items[k] * fprice[k])
total += items[k] * fprice[k]
print("total : {}".format(total))
print_summary (bought,price_of)
3 Avocado : 15
2 Banana : 6
1 Cherries : 7
total : 28

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
在這里你想根據(jù)鍵值以相反的順序?qū)δ愕淖值溥M(jìn)行排序,所以你必須在你的代碼中添加它。這里主要關(guān)注的是排序,所以我以簡單的方式完成了值的乘法。
bought = {'Banana':2, 'Avocado':3, 'Cherries':1}
price_of = {'Apple': 6,
'Avocado': 5,
'Banana': 3,
'Blackberries': 10,
'Blueberries': 12,
'Cherries': 7,
'Pineapple': 7}
bought['Banana'] *= price_of['Banana']
bought['Avocado'] *= price_of['Avocado']
bought['Cherries'] *= price_of['Cherries']
lst = list()
for k,v in bought.items():
newtup = (v,k)
lst.append(newtup)
lst = sorted(lst, reverse = True)
n=3
total = 0
for k,v in lst:
print(n,' ',v,' : ',k)
total = total + k
n = n-1
print('total :', total)
此代碼的輸出是:
3 Avocado : 15
2 Cherries : 7
1 Banana : 6
total : 28

TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊
for fruit, quantity in sorted(bought.items()):
print(f"{quantity} {fruit} : {quantity * price_of[fruit]}")
print(f"total : {sum(quantity * price_of[fruit] for fruit, quantity in bought.items())}")
添加回答
舉報(bào)