简体   繁体   中英

How do I compare the strings in a txt.file to my dictionary values (the values are integers) and calculate the sum

The title of my question might be a bit confusing - maybe that's because I am a little confused myself.

I have a task to create a small billing system for a restaurant (It is not a real restaurant). I have 3 text files. The first one being the menu.txt. In the file, each line consists of the name of a dish and its price, seperated by a comma. Then I have 2 order files order1.txt and order2.txt Each line contains an item from the menu that has been ordered.

My own suggestion to this task was to put the menu file into a list and then make it a dictionary.

This is my solution:

def compute_total(mfile, ofile):
    dictionary = {}
    newlist = []
 
    with open('menu.txt') as f:
        for line in f:
            line = line.replace(',', '')
            newlist.append(line.split())
               
        for strings in newlist:
           dictionary[strings[0]] = strings[1]

I feel like I am on the right way with this but I don't really know how make code from here. Because I know that I want to somehow see if for example: order1 is in the dictionary (menu) and then calculate the values (prices) of the dishes.

I was thinking maybe something like this below, but it does not work and I am stuck.

    for k, v in dictionary.items():
        if int(k) in dictionary.items():
            Dvalues.append(v)

I hope you can give me some advice to get going. I am a novice so I really hope you would take some time to help me with small problem (for you) like this.

Best regards, SEE

Python's csv package is great for dealing with comma separated files. Instead of having to parse each line manually, the csv module will be able to convert each line to a list of values that were previously separated by commas. Then, you can just use parallel assignment to get the items and prices for each line, and store them in the dictionary:

with open('menu.txt') as f:
    for line in f:
        item, price = csv.reader(line, quotechar="'", delimiter=",")
        dictionary[item] = price

Now that you've stored all the menu items in the dictionary, all you have to do is read each item line from the other text files, pass that item to your dictionary, get back the price, and add it to the sum:

order1_total = 0
with open(mfile) as f:
    for line in f:
        item = line      
        order1_total += dictionary[item]
           

Don't forget to add the line import csv to the top of your program. Hope it helps! Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM