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

Alan Gauld alan.gauld at btinternet.com
Thu Sep 8 16:03:33 CEST 2011


On 08/09/11 11:58, 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'
>

You could have done that in one line if you preferred:

 > p = {
  'bp1':'xxx',
  'bp2':'ooo'
    etc/...
  'pw':'kkk'
}


> 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.

Consider using a shelve (See the shelve module)
It is basically a file that you can treat as a dictionary...

Try:

 >>> import shelve
 >>> help(shelve)

For examples and info.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list