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

Richard D. Moores rdmoores at gmail.com
Thu Sep 8 15:40:24 CEST 2011

On Thu, Sep 8, 2011 at 04:43, Peter Otten <__peter__ at web.de> wrote:
> 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.

Thanks Peter!

You made it a lot easier than I thought it would be. Please see
<http://pastebin.com/NbzBNMDW> for the script's current incarnation.
The text of the demo data file is quoted in the script, lines 6-13. It
doesn't seem I need to use the json module, though I want to learn it

The data file very easily edited. However, as the number of lines gets
large (maybe 100?) I'll need a way to determine if the new key is
already in the file. So I'll be working on a script that I can use to
safely add lines to the the file, by keeping all the keys unique.


More information about the Tutor mailing list