[英]Python: How to store multiple values for one dictionary key
我想在字典中存儲配料列表,使用配料名稱作為關鍵字,並將配料數量和度量值都存儲為值。 例如,我希望能夠執行以下操作:
ingredientList = {'flour' 500 grams, 'tomato' 10, 'mozzarella' 250 grams}
使用“番茄”鍵,西紅柿沒有測量值,只有數量。 我可以在Python中實現嗎? 有替代的或更有效的方法來解決此問題嗎?
如果您要使用列表,請使用列表:
ingredientList = {'flour': [500,"grams"], 'tomato':[10], 'mozzarella' :[250, "grams"]}
獲取物品:
weight ,meas = ingredientList['flour']
print(weight,meas)
(500, 'grams')
如果您只想更新ingredientList[key].append(item)
您可以使用另一個字典。
ingredientList = {
'flour': {'quantity': 500, 'measurement': 'grams'},
'tomato': {'quantity': 10},
'mozzarella': {'quantity': 250, 'measurement': 'grams'}
}
然后,您可以像這樣訪問它們:
print ingredientList['mozzarella']['quantity']
>>> 250
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.