How to extract keys with its values and add values to print the total in python dictionary?

Viewed 148

Here I have menu of a restaurant and its price. I want to check orders and add prices and print total price for order. But I am unable to extract values of keys for specific orders. How to show orders and its price together like

malesuada : $14.00
Sorry, we don't have pizza
maecenas : $12.00

total price: $26.00

menu_items = {
    'nulla aliquam': 15.00,
    'malesuada': 14.00,
    'feugiat ipsum': 9.00,
    'maecenas': 12.00,
    'fermentum mass': 23.00
}
ordered_items = {
    'maecenas',
    'pizza',
    'malesuada'
}
for item in ordered_items:
    if item in menu_items.keys():
      print(item)
    else:
      print("sorry we dont have ",item)

2 Answers

Two things:

  • You don't need to use .keys() to check if a key exists in a dictionary

  • You access the price using dictionary indexing: dictionary[key] -> value

total = 0
for item in ordered_items:
    if item in menu_items:
        print('{} : ${:2f}'.format(item, menu_items[item]))
        total += menu_items[item]
    else:
        print('Sorry we don\'t have {}'.format(item))

print('Total price : ${:2f}'.format(total))

You can use a list comprehension to get the menu prices of the items in ordered_items, please note that the structure you have created for ordered_items is a set not a dictionary.

menu_items = {
    'nulla aliquam': 15.00,
    'malesuada': 14.00,
    'feugiat ipsum': 9.00,
    'maecenas': 12.00,
    'fermentum mass': 23.00
}
ordered_items = {
    'maecenas',
    'pizza',
    'malesuada'
}

totalPrice = sum([v for k,v in menu_items.items() if k in ordered_items])
print(totalPrice)

Output:

26.0

The list comprehension is just a nicer way of doing the below for loop:

Edit For your specification of printing of each item in the order.

total_price = 0 
for item in ordered_items:
    if item in menu_items:
        print(f"{item} : ${menu_items[item]} ")
        total_price += menu_items[item]
    else:
        print(f"Sorry, we don't have {item}")
print(f'Total : ${total_price}')

Output:

maecenas : $12.0

Sorry, we don't have pizza

malesuada : $14.0

Total : $26.0

To print all this on one line, append each statement to one string on each loop and print this at the end:

total_price = 0 
printString = ''
for item in ordered_items:
    if item in menu_items:
        printString += f"{item} : ${menu_items[item]} "
#        print(f"{item} : ${menu_items[item]} ")
        total_price += menu_items[item]
    else:
#        print(f"Sorry, we don't have {item}")
        printString += f"Sorry, we don't have {item} "
#print(f'Total : ${total_price}')
printString +=  f"Total : ${total_price} "

print(printString)

Output:

maecenas : $12.0 Sorry, we don't have pizza malesuada : $14.0 Total : $26.0

Related