killerstick1 killerstick1 - 4 months ago 13
Python Question

permanently store a value to be used in a dict

I have a dictionary

self.total = defaultdict(int)
in my Order class that is used to input and print totals of every item that is ordered in my ordering system. Object are stored as

coffee_available=[Coffee(1, "1: Flat White", 3.50),
Coffee(2, "2: Long Black", 3.50),
Coffee(3, "3: Cappuccino", 4.00),
Coffee(4, "4: Espresso", 3.25),
Coffee(5, "5: Latte", 3.50)]
`


and the way I "order" these objects is by calling a function in my order class

def order(self, order_amount, coffee_id):

self.total[coffee_id] += order_amount


and i print each item type and their respective order amounts by using another function in my order class

def print_order(self):
print(" ")
print("Coffee Type\t\tAmount of Times ordered")
print("-----------\t\t-----------------------")
for coffee in coffee_available:

print("{}\t- - -\t {} ".format(coffee.coffee_type, self.total[coffee.coffee_id]))


this works well as each time my code is run in the same session it stores the
order_amount
value each time and displays it correctly, the only problem is that if i terminate the program it doesn't store the data for when i open it next. If I were to permanently store data how would I do it and what should i permanently store?

Answer

So you can make any python object to persist in a file using pickle. So lets say you want to persist the total

import pickle
# total is a dictionary
# to store it in a file
with open('total_dictionary.pickle', 'wb') as handle:
  pickle.dump(total, handle)

# lets say program terminated here

Now,

# to load it, if it was previously stored
import pickle
with open('total_dictionary.pickle', 'rb') as handle:
  total = pickle.load(handle)

# total dictionary is exactly same even if the program terminated.

So, your order method updates your self.total and print_order just views it. So basically you need to store the self.total after every update (order call). And, in the initializer of the class where you first declare self.total, you need to initialze self.total with dictionary loaded from pickled file (if it exists)


Just to be little more specific:

import pickle
..
def order(self, order_amount, coffee_id):
    self.total[coffee_id] += order_amount
    with open('total_dictionary.pickle', 'w') as handle:
        pickle.dump(total, handle)

and in initializer of the Order class

def __init__(self):
    ...
    if os.path.exist("total_dictionary.pickle"):
        with open('total_dictionary.pickle', 'r') as handle:
            total = pickle.load(handle)
    else:
        total = defaultdict(int)
    ...

You can remove/delete total_dictionary.pickle to reset.

Hope it helps :)