'Python - How to get each item multiplied by the amount the user inputs? [closed]

I have this python3 code, it's a simple grocery list and the user can type the items he wants to buy and then the output is the total cost. But instead of repeating each item multiple times, I want the user to input the amount like..."2chicken, 2tomato" instead of "chicken, chicken, tomato, tomato"..how do i do this?

items_dict={"chicken": 50, "fish":30, "tomato":12, "chips":5}
print("Our shop has", tuple(items_dict))
prompt=input("What will you buy?\n").split(', ')
total_price=0

for items in prompt:
    try:
        total_price += items_dict[items]
    except:
        total_price="Some items aren't available to buy."
        break
print ("You have to pay", total_price, "EGP")

Input: 2chicken, 22tomato, 100chips

Expected Output: You have to pay 864 EGP.



Solution 1:[1]

I would have approach this using re.match in the following way:

import re
items_dict={"chicken": 50, "fish":30, "tomato":12, "chips":5}
print("Our shop has", tuple(items_dict))
prompt=input("What will you buy?\n").split(', ')

total_price=0

for items in prompt:
    match = re.match("(\d+)(\w+)", items) # Here group(1) => (\d+) will match the quantity of item and 
                                          # group(2) => (\w+) will match the name of product.
    try:
        total_price += (int(match.group(1))*items_dict[match.group(2)])
    except:
        total_price="Some items aren't available to buy."
        
print ("You have to pay", total_price, "EGP")

Output:

Our shop has ('chicken', 'fish', 'tomato', 'chips')
What will you buy?
2chicken, 22tomato, 100chips
You have to pay 864 EGP

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1