[Tutor] need advice about a dictionary ({})

Christian Witts cwitts at compuscan.co.za
Thu Sep 8 13:36:46 CEST 2011


On 2011/09/08 12:58 PM, Richard D. Moores wrote:
> I've succeeded in writing a dictionary ({}) that I can use as a small
> personal phone book. The dictionary (very shortened and simplified)
> looks like this in the script;
>
> p = {}
>
> p['bp1'] = 'xxx'
> p['bp2'] = 'ooo'
> p['ch'] = 'zzz'
> p['me'] = 'aaa'
> p['mg'] = 'vvv'
> p['pu1'] = 'bbb'
> p['pu2'] = 'ccc'
> p['pw'] = 'kkk'
>
> I have a function that enables the user to enter 'bp', for example,
> and return both 'xxx' and 'ooo'.
>
> (The keys are initials; I've disguised the values, each of which of
> course are   name, home number, mobile number, speed dial number,
> etc.)
>
> But I'd like to put the lines of the dictionary in a text file so that
> I can add key/value items to it by writing to it with another script.
> I think I can do that, but I need some hints about how to get  the
> script to access the text file in a way that lets the user look up a
> phone number. I'm thinking that the script needs to recreate the
> dictionary each time it's called, but I don't know how to do that.
>
> Thanks,
>
> Dick Moores
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

You could pickle your dictionary object which will give you the 
persistence and then when your script starts up you can unpickle the 
file if it exists else create a new one. Of course if you make any 
changes to your object you'll need to pickle it once your app finishes 
otherwise new changes won't be written out.

With just a plain text file you can also just grep the info out
$ cat test.file
bp1:xxx|yyy
bp2:ooo|ppp
ch:zzz|asf
me:agkjh|agjh
$ grep -i ^bp* test.file
bp1:xxx|yyy
bp2:ooo|ppp
$ grep -i ^BP* test.file
bp1:xxx|yyy
bp2:ooo|ppp

-- 

Christian Witts
Python Developer

//
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110908/8f16555e/attachment.html>


More information about the Tutor mailing list