how do I save a dictionary, (below), to a txt file thats is in a tabular format?
i also need to be able to rload the txt file back into its dictionary form...

catalog = { 1:["Bread", 1.50, 10 ], 2:["Cheese", 5.00, 5], 3:["Apples", 2.50,12] }

eg.

1 Bread 1.50 10
2 Cheese 5.00 5
3 Apples 2.50 12

thanks in advance

Recommended Answers

All 10 Replies

Since this looks a lot like homework, please show us at least some coding effort on your part!

HINT:

line = "1 Bread 1.50 10"
key, food, cost, quantity = line.split()

OK then, I was given this program and I've made alterations to it so as to enable new items, modifications to item etc... i need to be able to save the catalogue after the session so that it can also be re-loaded afterwards. here's the program:

'''maintain a catalog'''

def main():
    global catalog

    loadCatalog()
    while True:
        pick = showMenu()
        if pick == 0:
            break
        elif pick == 1:
            sellItem()
        elif pick == 2:
            buyItem()
        elif pick == 3:
            modPrice()
        elif pick == 4:
            newItem()
        else:
            print "Invalid selection"
    saveCatalog()

def showMenu():
    global catalog

    while True:
        print "Catalog:\n\t%6s %12s %8s %8s" % ( "ItemID", "Item", "Price", "Stock" )
        for k in catalog.keys():
            print "\t%6d %12s %8s %8d" % (k,catalog[k][0], str("$%0.2f" % catalog[k][1]), catalog[k][2])

        try:
            pick = int(raw_input('''
Enter selection:
0 - Quit
1 - sell Item
2 - buy Item
3 - modify Price
4 - new Item

Selection : ''' ))
        except:
            print "Pick must be an integer\n"
            continue
        return pick

def sellItem():
    global catalog
    print "Sell Item"

    try:
        itemID = int(raw_input("Which item? "))
        if itemID in catalog.keys():
            howMany = int(raw_input("How many? "))
            if 0 < howMany <= catalog[itemID][2]:
                catalog[itemID][2] -= howMany
                print "Price for %d %s is $%0.2f" % ( howMany, catalog[itemID][0],catalog[itemID][1]*howMany )
            else:
                print "Can't sell %d %s" % ( howMany, catalog[itemID][0] ) 
        else:
            print "Invalid itemID"
    except:
        print "Bad value entered"
    print

def buyItem():
    global catalog
    print "Buy Item"
    try:
        itemID = int(raw_input("Which item? "))
        if itemID in catalog.keys():
            howMany = int(raw_input("How many? "))
            if 0 < howMany:
                catalog[itemID][2] += howMany
            else:
                print "Can't buy %d %s" % ( howMany, catalog[itemID][0] ) 
        else:
            print "Invalid itemID"
    except:
        print "Bad value entered"
    print

def modPrice():
    global catalog
    print "Price Change"
    try:
        itemID = int(raw_input("Which item? "))
        if itemID in catalog.keys():
            modPrice = float(raw_input("New price? "))
            if 0 < modPrice:
                catalog[itemID][1] = modPrice
            else:
                print "Invalid price entered." 
        else:
            print "Invalid itemID"
    except:
        print "Bad value entered"
    print

def newItem():
    global catalogue
    print "New Item"
    try:
        itemID = -1
        itemID = int(raw_input("Enter Item ID that isn't already assigned: "))
        itemName = raw_input("Enter item name: ")
        itemPrice = float(raw_input("Enter item price:$ "))
        stock = int(raw_input("Enter quantity of stock: "))

        catalog[itemID] = (itemName, itemPrice, stock)

    except:
        print "Bad value entered"
    print
    
def loadCatalog():
    global catalog
    catalog = { 1:["Bread", 1.50, 10 ], 2:["Cheese", 5.00, 5], 3:["Apples", 2.50,12] }

def saveCatalog():
    global catalog
    file = open("item_File.txt", "w")
    file.close()



if __name__ == "__main__":
    main()

Should I use a txt file and just append to it instead of using a dictionary? would that be simpler?

As your data gets larger a dictionary allows for fast look-ups. You can save and reload a dictionary complete with module pickle.

Or my be save in database like SQLite3/MySQL

PLEASE HELP!! could someone pls implement a pickle module into my program and post it for me...
i've been struggling for hours without any success...

I have seen this somewhere ...

# use module pickle to dump and load complete objects
# like dictionaries
# modified to work with Python2 and Python3 versions

import pickle

catalog = {
1:["Bread", 1.50, 10 ],
2:["Cheese", 5.00, 5],
3:["Apple", 2.50,12]
}

# pickle dump the dictionary
fh_out = open("cat1.dat", "wb")
# default protocol is zero
# -1 gives highest prototcol and smallest data file size
pickle.dump(catalog, fh_out, protocol=0)
fh_out.close()

# test it ...
# pickle load the dictionary
fh_in = open("cat1.dat", "rb")
catalog2 = pickle.load(fh_in)
fh_in.close()

print(catalog)

print(catalog2)

"""result -->
{1: ['Bread', 1.5, 10], 2: ['Cheese', 5.0, 5], 3: ['Apple', 2.5, 12]}
{1: ['Bread', 1.5, 10], 2: ['Cheese', 5.0, 5], 3: ['Apple', 2.5, 12]}
"""

Yeah, use the cPickle module. It's easy, simple, fast, and good for these kinda stuff

In Python3 module cPickle has become the standard module pickle.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.