Python Forum

Full Version: Python Coding Homework Help "Grocery Store Receipt"
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I was assigned to create a "receipt" type output for homework using 2 dictionaries, one for the quantity of items and the item, and the other for the price of the item and the item. We have to use external text documents put into the dictionaries. I am getting the dictionaries to work and output what they are supposed to, however, I am having trouble trying to output these onto the console, since they won't print at all. The issue I am having is the part where you process the grocery list, so if you could help me that would be great!

    
grocery_dictionary = {}
gro_inv_file = open("groc_test2.txt", "r")

for line in gro_inv_file:
    line = line.strip()
    product = line.split()
    #print(product)
    key = product[0]
    value = float(product[1])
    #print(key,value)
    grocery_dictionary[key] = value

print(grocery_dictionary)
#gro_inv_file.close()


#=====================================================Second Dictionary=========

grocery_dictionary2 = {}
gro_inv_file2 = open("groc_list_test.txt", "r")

for line2 in gro_inv_file2:
    line2 = line2.strip()
    product2 = line2.split()
    #print(product2)
    key2 = product2[1]
    value2 = product2[0]
    #print(value2,number)
    grocery_dictionary2[key2] = value2

print(grocery_dictionary2)
#gro_inv_file2.close()


#====================================== Process our grocery list =============

print("{:6s} {:7s} {:2s} {:6s} {:2s} {:5s}".format("QTY","ITEM", "@", "PPU", "=", "Total")) # Top of reciept

print(grocery_dictionary2[key2])


#
#final_dictionary = {}
#
#running_total = 0
#
#for item in final_dictionary:
#   # print(item)
#    quantity = grocery_dictionary2[value2]
#    grocery_item = grocery_dictionary[key]
#    unit_price = float(grocery_dictionary[value])
#    
#    extension = quantity*unit_price
#    
#    
#    print("{:3d} {:^10} @  {:4.2f}   = {:6.2f}".format(quantity, grocery_item, unit_price, extension))
#    running_total += extension
#    
#    
#print("Total due: ", running_total)
What do you mean by "won't print at all?" Do you get an error?

PS: grocery_dictionary1/grocery_dictionary2 are awful names. price_dictionary and quantity_dictionary are much better. Some people would even use prices and quantities.
It prints the "top of receipt" (the list), however the part thats commented out ("final dictionary") will not print (when it isn't commented out). I think it is because I pulled the data from the other two dictionaries incorrectly, but I'm not exactly sure. About the names, sorry, i'm still sort of new to coding.
it's because final_dictionary is empty, i.e. you iterate over empty dict. Also note that value, value2 and key retain their last value from the loop when you iterate over second file.