[英]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.