简体   繁体   中英

Python: How to store multiple values for one dictionary key

I want to store a list of ingredients in a dictionary, using the ingredient name as the key and storing both the ingredient quantity and measurement as values. For example, I would like to be able to do something like this:

ingredientList = {'flour' 500 grams, 'tomato' 10, 'mozzarella' 250 grams}

With the 'tomato' key, tomatoes do not have a measurement, only a quantity. Would I be able to achieve this in Python? Is there an alternate or more efficient way of going about this?

If you want lists just use lists:

ingredientList = {'flour': [500,"grams"], 'tomato':[10], 'mozzarella' :[250, "grams"]}

To get the items:

weight ,meas = ingredientList['flour']
print(weight,meas)
(500, 'grams')

If you want to update just ingredientList[key].append(item)

You could use another dict.

ingredientList = {
    'flour': {'quantity': 500, 'measurement': 'grams'},
    'tomato': {'quantity': 10},
    'mozzarella': {'quantity': 250, 'measurement': 'grams'}
}

Then you could access them like this:

print ingredientList['mozzarella']['quantity']
>>> 250

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM