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

Peter Otten __peter__ at web.de
Thu Sep 8 13:43:34 CEST 2011


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.

Start with a simple file format. If you don't allow "=" in the key and "\n" 
in either key or value 

bp1=xxx
bp2=ooo
...
pw=kkk

should do. I suppose you know how to read a file one line at a time? Before 
you add the line into the dictionary you have to separate key and value 
(str.partition() may help with that) and remove the trailing newline from 
the value. If you need more flexibility look into the json module. This 
makes reading and writing the file even easier, and while the format is a 
bit more complex than key=value

>>> print json.dumps(p, indent=2)
{
  "me": "aaa",
  "mg": "vvv",
  "ch": "zzz",
  "pw": "kkk",
  "bp1": "xxx",
  "bp2": "ooo",
  "pu1": "bbb",
  "pu2": "ccc"
}

it can still be edited by a human.



More information about the Tutor mailing list