You can pass the customerList (as string) directly to the function that calculates the prices as follows.
The routine converts the string to a list of sublist of the form (for your data):
[['potato', 'X', '8'], ['orange', 'X', '7'], ['rice', 'X', '13'], ['bread', 'X', '13']]
Function to calculate Value:
def calc_purchase_value(customerList_contents, price_list):
" Compute purchase value "
# convert customerList_contents to a list of list
purchase_list = [x.split() for x in customerList_contents.split('\n') if x.strip()]
# Iterate through the purchase_list looking up items in the price list
# Each sublist will be of the form [item, 'X', cnt]
return sum([price_list.get(item, 0) * int(cnt) for item, x, cnt in purchase_list])
Example of Usage
Using your customerList_contents (different strings will be read from file)
customerList_contents = """
potato X 8
orange X 7
rice X 13
bread X 13
"""
price_list = {"rice": 2.10,
"potato":4.21,
"orange":3.31,
"eggs":1.92,
"cheese":8.10,
"chicken":5.22}
print(calc_purchase_value(purchase_list, price_list))
#>> 84.15
Complete Solution
import glob
import os
import json
def readShopping():
" Reads each customer shopping list, returning result as a geneerator "
for file in glob.glob('./shoppinglists/*.txt'):
with open(file,'r') as customerList:
contents = customerList.read()
# return file path and contents
yield file, contents
def calc_purchase_value(customerList_contents, price_list):
" Compute purchase value "
# convert customerList_contents to a list of list
purchase_list = [x.split() for x in customerList_contents.split('\n') if x.strip()]
# Iterate through the purchase_list looking up items in the price list
# Each sublist will be of the form [item, 'X', cnt]
return sum([price_list.get(item, 0) * int(cnt) for item, x, cnt in purchase_list])
def get_prices():
" Reads prices from JSON file "
with open('./shoppinglists/pricelist.json') as json_file:
return json.load(json_file)
# - Get prices from JSON file
price_list = get_prices()
for file, contents in readShopping():
# file - path to customer file
# contents - contents of customer file
# Extract customer name from file path
basename = os.path.basename(file)
customer_name = os.path.splitext(basename)[0]
# Total price: based upon shopping list and price list
total_price = calc_purchase_value(contents, price_list)
# Show results
print('Customer {} total is: {:.2f}'.format(customer_name, total_price))
In the above, I have 2 text files in folder shoppinglists "Mary.txt" and "James.txt" (you will have say 50 or more).
Prices list is stored in pricelist.json
Contents of Mary.txt
orange X 3
rice X 2
potato X 3
eggs X 2
Contents of James.txt
potato X 8
orange X 7
rice X 13
bread X 13
Output
Customer james total is: 84.15
Customer mary total is: 30.60