Jan-10-2018, 03:59 PM
(Jan-10-2018, 03:14 PM)TFish Wrote: How would i go about the selection of the cost from the Dictionary.
You can reference items in a dictionary with it's "key" name. In other words, dictionaries map keys to values. So if you wanted to look up people by their age you might have a dictionary such as this:
ages = { "Joe": 32, "Sandy": 16, "Bob": 23, "Janice": 35 } # you can then get each person's age with their name: ages["Joe"]One way to do this with foods, is making a dictionary that maps the names of foods to a dictionary of their details:
# foods is a dict of dict's. Each food is referenced by it's name... foods = { "Wheat Bread": { "cost": 2.50, "calories": 300, "servings": 18 }, "Pepsi": { "cost": 1.00, "calories": 1000, "servings": 1} } bread = foods["Wheat Bread"] print("Bread costs {0} per loaf".format(bread["cost"])) # to run through all foods you can use a for-loop for name, info in foods.items(): print("{0} costs {1} dollars".format(name, info["cost"]))
Output:> python.exe food.py
Bread costs 2.5 per loaf
Wheat Bread costs 2.5 dollars
Pepsi costs 1.0 dollars