Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Grocery List Program
#6
(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
Reply


Messages In This Thread
Grocery List Program - by TFish - Jan-09-2018, 05:53 PM
RE: Grocery List Program - by mpd - Jan-09-2018, 11:10 PM
RE: Grocery List Program - by TFish - Jan-10-2018, 04:00 AM
RE: Grocery List Program - by mpd - Jan-10-2018, 12:35 PM
RE: Grocery List Program - by TFish - Jan-10-2018, 03:14 PM
RE: Grocery List Program - by mpd - Jan-10-2018, 03:59 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Program to find Mode of a list PythonBoy 6 1,181 Sep-12-2023, 09:31 AM
Last Post: PythonBoy
  Create a program that PING a list of IPs skaailet 7 6,491 Mar-26-2020, 10:46 PM
Last Post: snippsat
  how to open program file .exe from list SayHiii 2 2,480 Dec-11-2019, 01:28 AM
Last Post: SayHiii
  creating a list during program execution. hobbyprogrammer 2 2,446 Jan-26-2019, 09:06 PM
Last Post: hobbyprogrammer

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020