Capy
Capy

Reputation: 35

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?

Upvotes: 0

Views: 5663

Answers (2)

d6bels
d6bels

Reputation: 1482

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

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180532

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)

Upvotes: 1

Related Questions