Let’s say I have a dictionary that receives a three inputs from the user: item name, item price, and item quantity. How can I make a for-loop that produces the following:
Cat 20.0 2
Dog 30.0 3
Fish 200.00 4
Here's my code:
grocery_list = {}
print(" MY NEW AND IMPROVED GROCERY LIST")
while True:
def choice(): # main function
print("======================================")
print("What would you like to do?"
"\n1 - Add an Item"
"\n2 - Remove an Item"
"\n3 - Print entire List"
"\n4 - Calculate Cost"
"\n5 - Exit program")
user = int(input("\nChoice:"))
if user == 1:
print("======================================"
"\nADD AN ITEM"
"\n"
"\nGive the following information:")
name = str(input("Name:").lower())
price = float(input("Price:"))
quan = int(input("Quantity:"))
grocery_list[name] = {"name": name, "price": price, "quan": quan}
elif user == 2:
print("======================================"
"\nREMOVE AN ITEM"
"\nWhat would you like to remove?")
rmv = str(input("Item Name:").lower())
if rmv in grocery_list:
del grocery_list[rmv]
elif user == 3:
for values in grocery_list.values():
print(values)
The output would then be:
{'name': 'cat', 'price': 2.0, 'quan': 3}
{'name': 'fish', 'price': 3.0, 'quan': 2}
I tried creating a for-loop but it wouldn’t work.
CodePudding user response:
Your grocery_list (dict) is:
{
name1: {"name": name1, "price": price, "quan": quan},
name2: {"name": name2, "price": price, "quan": quan}
}
To iterate it, change step 3 to:
for item in grocery_list:
print(grocery_list[item]['name'], grocery_list[item]['price'], grocery_list[item]['quan'])
CodePudding user response:
grocery_list is a dictionary of dictionaries. In case you want to output the values of this dictionaries, you shall once again iterate over the values of this dictionaries:
elif user == 3:
for values in grocery_list.values():
for value in values.values()
print(value)
OR if you want the exact same output you mentioned in the beginning:
elif user == 3:
for values in grocery_list.values():
l = []
for value in values.values()
l.append(value)
print('\t'.join(l))