[Tutor] how to create a persistent dictionary w/ cpickle?

Dave Angel davea at ieee.org
Thu Sep 9 00:14:45 CEST 2010


  On 2:59 PM, Carter Danforth wrote:
> Hi, I'm trying to a create a basic addressbook for practice. I'm using a
> dictionary with cpickle, though I'm not sure how to persistently store each
> instance in the dictionary. Below is the code I have so far.
>
> If I run it once and add a contact and the details, it's fine. p.load(f)
> shows the details next time I run it, but if I add another contact, and run
> it again, the previous key:value doesn't show. It gets replaced by the new
> one.
>
> How can I fix this so that it adds the new key:value to the dictionary
> instead of replacing the existing one? Appreciate any help, thanks.
>
> import cPickle as p
> addressbook = 'addressbook.data'
> f = file(addressbook, 'r+')
>
> class address:
>      def __init__(self, name, tel, email):
>          self.name = name
>          self.tel = tel
>          self.email = email
>
>          ab = {self.name : self.tel}
>
>          f = file(addressbook, 'r+')
>          p.dump(ab, f)
>
> print p.load(f)
> x = raw_input()
>
> if x == 'add':
>      name = raw_input('\nName: ')
>      tel = raw_input('Tel: ')
>      email = raw_input('Email: ')
>
>      contact = address(name, tel, email)
>
I have no clue what you're trying to do with that address object;  it's 
confusing initialization with persistence, and you create such an 
object, but never actually use it.  I would remove any reference to the 
address book from that object.  I'd also rename it to Address, since 
class names are supposed to be uppercase (PEP8)

But anyway, in your flow, you do a p.load(), but never save the result.  
Every time you save to the addressbook file, you start over with just 
the one entry.

One way to fix this is to save the p.load() result as a variable, 
presumably of type dictionary, then add the 'contact' to that 
dictionary, and at the end of the script, save that variable with 
p.dump(addresses, f)

addresses =   p.load(f)

interact with user --
            addresses[name] = Address(name, tel, email)

p.dump(addresses, f)

I also don' t know how you get away with running your script the first 
time, since it blows up if there's no existing pickle file.

DaveA



More information about the Tutor mailing list