Pickle A Bag Container (Python)

vegaseat 4 Tallied Votes 248 Views Share

Let's say you have a whole bunch of nicely named lists and want to save them all and their names in a pickle file. One solution can be to store these lists and their names in a Bag container class and pickle the bag instance object. Now you can use the lists and their names in another program, as long as you insert class Bag_Dict in that program and load the pickle file.

'''pickle_bag_of lists.py
if you have a whole bunch of named lists and want to save them all
in a pickle file, you can store these lists and their names in a 
Bag container class and pickle the bag instance object
tested with Python27 and Python33  by vegaseat  20nov2012
'''

import pickle

class Bag_Dict(object):
    """
    simple key mapped container for lists that belong together
    the name of each list is the key
    list1 = [1, 2, 3],
    list2 = [4, 5, 6],
    ...
    """
    def __init__(self, **kwargs):
        # allows class instance operations via internal dictionary
        self.__dict__.update(kwargs)

    def show(self):
        """
        show the present contents, sorted by key (name of list)
        """
        contents = sorted([(k, v) for k, v in self.__dict__.items()])
        for key, val in contents:
            print("%s = %s" % (key, val))
            
    def bag_content(self):
        """
        return the internal class dictionary
        """
        return self.__dict__
    
    def __call__(self, search):
        """
        find a search value in any of the bag's list items
        """
        for key in self.bag_content():
            if search in self.bag_content()[key]:
                print("%s is in list %s" % (search, key))
        

# Fill the bag with all your list assignments 
# you want to keep together.
# If you want to use a list's name, just use 
# for instance bag.animal instead of animal

bag = Bag_Dict(
animal = ['duck', 'chicken', 'horse'],
drinks = ['coke', 'tea', 'coffee'],
foods = ['butter', 'bread', 'meat', 'fruit']
)

# add one more list
bag.plants = ['rose', 'mint']

# check what's in the bag
print("Lists in the bag:")
bag.show()

print('-'*40)

# search the bag for 'chicken'
print("Search the bag for 'chicken':")
bag('chicken')

print('-'*40)

# remember, if you want to reference list animal just use bag.animal
print("What's in bag.animal?")
print(bag.animal)
print('or ' + '.'*10)
# or reassign ...
animal = bag.animal
print(animal)

print('='*40)

# save object bag to file with pickle
fname = "bag.pkl"
# pickle dump the bag object
with open(fname, "wb") as fout:
    # default protocol is zero
    # -1 gives highest prototcol and smallest data file size
    pickle.dump(bag, fout, protocol=0)

# pickle load the bag object back in (senses protocol)
# this way you can use the named lists in another program
# class Bag_Dict has to be inserted into the other program too 
with open(fname, "rb") as fin:
    bag2 = pickle.load(fin)

# test the contents of bag2
print("Lists in the bag2 (after pickle.load):")
bag2.show()

print('-'*40)

foods = bag2.foods
print(foods)
print(foods[1] + ' and ' + foods[0])

'''result ...
Lists in the bag:
animal = ['duck', 'chicken', 'horse']
drinks = ['coke', 'tea', 'coffee']
foods = ['butter', 'bread', 'meat', 'fruit']
plants = ['rose', 'mint']
----------------------------------------
Search the bag for 'chicken':
chicken is in list animal
----------------------------------------
What's in bag.animal?
['duck', 'chicken', 'horse']
or ..........
['duck', 'chicken', 'horse']
========================================
Lists in the bag2 (after pickle.load):
animal = ['duck', 'chicken', 'horse']
drinks = ['coke', 'tea', 'coffee']
foods = ['butter', 'bread', 'meat', 'fruit']
plants = ['rose', 'mint']
----------------------------------------
['butter', 'bread', 'meat', 'fruit']
bread and butter
'''
Lardmeister 461 Posting Virtuoso

A good example of using pickle with a class.

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.