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

2011-09-13 Thread Richard D. Moores
I'm the OP.

Nick Zarr, alias Jack Trades, has done something really marvelous.
He's made a thorough critique and refactoring of my phone_book.py, in
its last incarnation as http://pastebin.com/2wm4Vf1P. See
https://gist.github.com/1212290.

He'll be making that part of his blog
(http://pointlessprogramming.wordpress.com/), and may turn it into
an article.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Richard D. Moores
So I've done quite a bit more work. With phone_book.py the user can
not only access phone numbers by the person's initials, but can add
items to the data file. I've also solved the problem of adding a
person who's initials have already been used in a key.

I've pasted phone_book_for_pasting.py at http://pastebin.com/2wm4Vf1P.

I'd appreciate any comments, instructive criticism, etc.

Some have suggested using the shelve module. I looked at it but
couldn't see in detail how to use it. If someone could write a short
demo script, or send me to one that pretty much does what my
phone_book.py does, that would be terrific.

Dick Moores
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Jack Trades
On Sat, Sep 10, 2011 at 1:08 PM, Richard D. Moores rdmoo...@gmail.comwrote:

 So I've done quite a bit more work. With phone_book.py the user can
 not only access phone numbers by the person's initials, but can add
 items to the data file. I've also solved the problem of adding a
 person who's initials have already been used in a key.

 I've pasted phone_book_for_pasting.py at http://pastebin.com/2wm4Vf1P.

 I'd appreciate any comments, instructive criticism, etc.


It looks pretty good overall, though I didn't examine it too closely.  IMHO
there are some awkward bits which I think come from your representation of
the data.

I would probably make the phonebook itself a list, with each entry being a
dict.  Something like:

book = [
{'name':'Mark Sanders', 'cell':'422-318-2346', '
email':'msand...@stanfordalumni.org'},
{'name':'AAA', 'phone':'575-3992', 'phone2':'1-800-472-4630',
'notes':'Membership #422 260 0131863 00 8'},
#...
]


Then you can easily search your phone book by name, email, type of contact,
relation, etc.  A search by name would look like this:

def find_by_name(name):
  for entry in book:
if entry['name'] == name:
  return entry

find_by_name('Mark Sanders')
#== {'name':'Mark Sanders', 'cell':'422-318-2346', '
email':'msand...@stanfordalumni.org}

or a more general procedure for doing searches on your book could be:

def find(criteria, term):
  for entry in book:
if entry[criteria] == term:
  return entry

find('name', 'Mark Sanders')
#== {'name':'Mark Sanders', 'cell':'422-318-2346', '
email':'msand...@stanfordalumni.org}


Similarly you could search for initials by providing a to_initials
procedure:

def to_initials(name):
  return ''.join([i[0] for i in name.split(' ')])

def find_by_initials(initials):
  for entry in book:
if to_initials(entry['name']) == initials:
  return entry

find_by_initials('MS')
#== {'cell': '422-318-2346', 'name': 'Mark Sanders', 'email': '
msand...@stanfordalumni.org'}


Adding a new entry would then be as simple as:

def add_new_entry(entry, book):
  book.append(entry)


For storing data I would probably use Pickle, which would look something
like this:

from cPickle import load, dump

f = open('book.pk', 'w')
dump(book, f)
f.close()

and loading your book is similar

f = open('book.pk', 'r')
book = load(f)
f.close()


If you want a human readable storage format I would look into json, but
pickle has served me well for most purposes.  Surely you can store your
phonebook as plain text and parse it the way you have, but it's not
necessary to do that with all the tools that exist for that purpose.


-- 
Nick Zarczynski
Pointless Programming Blog http://pointlessprogramming.wordpress.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Richard D. Moores
Thanks so much, Jack. You've given me much to chew on.

I began phone_book.py without much need for it -- I already had an RTF
file with 786 lines that I grepped using a script I wrote with Tutor
help long ago. I used an RTF file instead of a text file so that any
URLs in it would be live. But I wanted to refresh what little I used
to know about dicts and see where I could go with it. It turns out to
be something I'll actually use for quickly looking up  phone numbers
of people (friends, relatives, doctors, etc.) and some businesses, and
the occasional address. For adding key=value items to the data file,
values can be copied as is from the RTF file.  It'll probably have
fewer than 100 entries.  Your idea doesn't seem efficient for me --
lots of typing and editing. But very interesting! I'll probably have
fewer than 100 entries.

Your pickle examples give me a start on using the cPickle module.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Richard D. Moores
Thanks so much, Jack. You've given me much to chew on.

I began phone_book.py without much need for it -- I already had an RTF
file with 786 lines that I grepped using a script I wrote with Tutor
help long ago. I used an RTF file instead of a text file so that any
URLs in it would be live. But I wanted to refresh what little I used
to know about dicts and see where I could go with it. It turns out to
be something I'll actually use for quickly looking up  phone numbers
of people (friends, relatives, doctors, etc.) and some businesses, and
the occasional address. For adding key=value items to the data file,
values can be copied as is from the RTF file.  It'll probably have
fewer than 100 entries.  Your idea doesn't seem efficient for me --
lots of typing and editing. But very interesting! I'll probably have
fewer than 100 entries.

Your pickle examples give me a start on using the cPickle module.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Richard D. Moores
Jack Trades (actually Nick Zarczynski) just sent me this link to a
Simple phone book app, and has agreed to let me post it to this
thread: https://gist.github.com/1208786#file_book.py

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Jack Trades
On Sat, Sep 10, 2011 at 4:36 PM, Richard D. Moores rdmoo...@gmail.comwrote:

 Your idea doesn't seem efficient for me --
 lots of typing and editing.


Not sure what you mean by that?  I've updated the gist with a quick 5min
implementation of a GUI using Tkinter and the approach I outlined.  I think
using a GUI is best way to minimize typing and editing in an app like
this.  You can find it here:

https://gist.github.com/1208786#file_book.py

If you're talking about re-entering all your data from your file, you would
write a script to do that.  This program assumes that you are starting from
scratch with a blank phone book.  If you would like help converting your
existing file, I'm sure I or others can help, but I'd need to see the
original file.

-- 
Nick Zarczynski
Pointless Programming Blog http://pointlessprogramming.wordpress.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Alan Gauld

On 10/09/11 19:08, Richard D. Moores wrote:


Some have suggested using the shelve module. I looked at it but
couldn't see in detail how to use it.


Did you read the help page? It says:

import shelve
d = shelve.open(filename) # open, with (g)dbm filename -- no suffix

d[key] = data   # store data at key
data = d[key]   # retrieve a COPY of the data at key
del d[key]  # delete data stored at key
flag = d.has_key(key)   # true if the key exists
list = d.keys() # a list of all existing keys (slow!)
d.close()   # close it


So you open the file and from that point on treat it exactly like a 
dictionary.


Then close the file at the end.

Now which part don't you understand?
The ony bit that migt confuse is the mention of gdbm filename which just 
means give it a filename without any suffix...just ignore the gdbm 
reference.


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

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Richard D. Moores
On Sat, Sep 10, 2011 at 15:32, Alan Gauld alan.ga...@btinternet.com wrote:
 On 10/09/11 19:08, Richard D. Moores wrote:

 Some have suggested using the shelve module. I looked at it but
 couldn't see in detail how to use it.

 Did you read the help page?

I did. I can see it would be a useful reference once I learned from
elsewhere how to use shelve.

 It says:

 import shelve
 d = shelve.open(filename) # open, with (g)dbm filename -- no suffix

 d[key] = data   # store data at key
 data = d[key]   # retrieve a COPY of the data at key
 del d[key]      # delete data stored at key
 flag = d.has_key(key)   # true if the key exists
 list = d.keys() # a list of all existing keys (slow!)
 d.close()       # close it


 So you open the file and from that point on treat it exactly like a
 dictionary.

I'm still a bit shaky about dictionaries.

 Then close the file at the end.

 Now which part don't you understand?

Much of what comes after that is beyond me.

 The ony bit that migt confuse is the mention of gdbm filename which just
 means give it a filename without any suffix...just ignore the gdbm
 reference.

Thanks for your encouragement Alan, but I'm still looking among my
Python books for a good exposition of shelve.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Alan Gauld

On 11/09/11 00:18, Richard D. Moores wrote:


So you open the file and from that point on treat it exactly like a
dictionary.


I'm still a bit shaky about dictionaries.


But you started the post with using a dictionary.

Shelve is just a dictionary that lives in a file instead of memory.
If you can put data into or read it out of a dictionary then you can do 
the same with shelve.


The only complexity is you have to open the file before sing it and 
close it when your done.



Much of what comes after that is beyond me.




Thanks for your encouragement Alan, but I'm still looking among my
Python books for a good exposition of shelve.


You probably won't find much in books because shelve has such a specific 
purpose. As a result there isn't much to say about it

if you've already covered dictionaries.

It's a file based dictionary. So read up on dictionaries.
Then just use it.

There are a few limitations with shelve but for most normal
cases you can ignore that and just use it like any normal
dictionary.

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

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Marc Tompkins
On Sat, Sep 10, 2011 at 4:18 PM, Richard D. Moores rdmoo...@gmail.comwrote:

 On Sat, Sep 10, 2011 at 15:32, Alan Gauld alan.ga...@btinternet.com
 wrote:

 So you open the file and from that point on treat it exactly like a
  dictionary.

 I'm still a bit shaky about dictionaries.

 That right there is the salient bit.  Using shelve is just like using a
dictionary; probably that's why you're finding the documentation sparse:
dictionaries are core Python, so they assume you know how to use them.
(First, catch your rabbit...)

I was about to write an introduction to dictionaries, but I realized it's
been done, and done better than I could.  I really recommend that you learn
them; I think that once you do, you'll find that they're a better fit in all
sorts of places where you've been using lists.  (Speaking from personal
experience...)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Alan Gauld

On 11/09/11 00:18, Richard D. Moores wrote:


Now which part don't you understand?


Much of what comes after that is beyond me.


I meant to add, you can pretty much ignore all the stuff at the end of 
the Help page about class definitions. You only need that if you intend 
to create your own specialised Shelf object. All you need to know is in 
the pseudocode bit that I posted.


open() the file
use the shelf like a dictionary
close() the file

And there are two main caveats given:
1) Don't try to edit mutable data objects (lists) in place.
   Extract them, modify them and replace them
2) Don't use the writeback=True setting when you open large data sets.

That's it.

Alan G.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Richard D. Moores
On Sat, Sep 10, 2011 at 17:34, Marc Tompkins marc.tompk...@gmail.com wrote:
 On Sat, Sep 10, 2011 at 4:18 PM, Richard D. Moores rdmoo...@gmail.com
 wrote:

 On Sat, Sep 10, 2011 at 15:32, Alan Gauld alan.ga...@btinternet.com
 wrote:

  So you open the file and from that point on treat it exactly like a
  dictionary.

 I'm still a bit shaky about dictionaries.

 That right there is the salient bit.  Using shelve is just like using a
 dictionary; probably that's why you're finding the documentation sparse:
 dictionaries are core Python, so they assume you know how to use them.
 (First, catch your rabbit...)

 I was about to write an introduction to dictionaries, but I realized it's
 been done, and done better than I could.  I really recommend that you learn
 them; I think that once you do, you'll find that they're a better fit in all
 sorts of places where you've been using lists.  (Speaking from personal
 experience...)

Well, I wrote a BIT shaky. I sure learned a lot writing my
phone_book.py, with important input from you . And am still pretty
happy with it. And dictionaries seem to be well-covered in some of the
Python books I have.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Richard D. Moores
On Sat, Sep 10, 2011 at 17:34, Alan Gauld alan.ga...@btinternet.com wrote:
 On 11/09/11 00:18, Richard D. Moores wrote:

 So you open the file and from that point on treat it exactly like a
 dictionary.

 I'm still a bit shaky about dictionaries.

 But you started the post with using a dictionary.

 Shelve is just a dictionary that lives in a file instead of memory.
 If you can put data into or read it out of a dictionary then you can do the
 same with shelve.

 The only complexity is you have to open the file before sing it and close it
 when your done.

 Much of what comes after that is beyond me.


 Thanks for your encouragement Alan, but I'm still looking among my
 Python books for a good exposition of shelve.

 You probably won't find much in books because shelve has such a specific
 purpose. As a result there isn't much to say about it
 if you've already covered dictionaries.

 It's a file based dictionary. So read up on dictionaries.
 Then just use it.

 There are a few limitations with shelve but for most normal
 cases you can ignore that and just use it like any normal
 dictionary.

OK, Alan, I really will give shelve a try.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Richard D. Moores
On Sat, Sep 10, 2011 at 15:15, Jack Trades jacktradespub...@gmail.com wrote:
 On Sat, Sep 10, 2011 at 4:36 PM, Richard D. Moores rdmoo...@gmail.com
 wrote:

 Your idea doesn't seem efficient for me --
 lots of typing and editing.

 Not sure what you mean by that?  I've updated the gist with a quick 5min
 implementation of a GUI using Tkinter and the approach I outlined.  I think
 using a GUI is best way to minimize typing and editing in an app like
 this.  You can find it here:

 https://gist.github.com/1208786#file_book.py

Using Python 2.7 for it, it seems to work fine, except that I can't
see how the GUI helps. It opens only when I use the g option to find
an entry already made. Useful for editing an entry, though.

As for the non-GUI script, I get this error no matter which choice I
make. I'm too dumb, and have forgotten too much of Python 2.x to
debug:

==
What's next:
(q)  Quit
(a)  Add new Entry
(v)  View all Entries
(s)  General Search
(si) Search by Initials
(sn) Search by Name

 q
Traceback (most recent call last):
  File c:\P32Working\Pickles\nicks_simple_phone_book_app.py, line
171, in module
main_loop()
  File c:\P32Working\Pickles\nicks_simple_phone_book_app.py, line
94, in main_loop
 )
  File string, line 1, in module
NameError: name 'q' is not defined
Process terminated with an exit code of 1


 If you're talking about re-entering all your data from your file, you would
 write a script to do that.

Ha! I would?

  This program assumes that you are starting from
 scratch with a blank phone book.  If you would like help converting your
 existing file, I'm sure I or others can help, but I'd need to see the
 original file.

I'll take you up on that. I'll have to edit it some first.

What I have now with grepping that 786-line RTF file is maximum
flexibility. A line in the file always begins with a name, with  at
least one phone number, then if a company, the hours they are
reachable by phone, possibly their web address, maybe an email
address, my contact there plus maybe her secretary. If a physician,
there might very well be his specialty, his nurse's name, mention of
who recommended him to me, etc. It seems that the format of info for
your way is set rigidly in advance, or am I wrong?

Dick




 --
 Nick Zarczynski
 Pointless Programming Blog


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-10 Thread Jack Trades

 Using Python 2.7 for it, it seems to work fine, except that I can't
 see how the GUI helps. It opens only when I use the g option to find
 an entry already made. Useful for editing an entry, though.


Well the idea would be to build the app as a full-blown GUI.  The GUI search
and edit functionality was just a proof-of-concept to show how that may
work.

I was just having some fun and seeing what I could do in less than an hour.
Turning this into a full blown app is not what I had in mind, though if you
want to build on it to learn I would be willing to help.



 As for the non-GUI script, I get this error no matter which choice I
 make. I'm too dumb, and have forgotten too much of Python 2.x to
 debug:

 ==
 What's next:
 (q)  Quit
 (a)  Add new Entry
 (v)  View all Entries
 (s)  General Search
 (si) Search by Initials
 (sn) Search by Name

  q
 Traceback (most recent call last):
  File c:\P32Working\Pickles\nicks_simple_phone_book_app.py, line
 171, in module
main_loop()
  File c:\P32Working\Pickles\nicks_simple_phone_book_app.py, line
 94, in main_loop
 )
  File string, line 1, in module
 NameError: name 'q' is not defined
 Process terminated with an exit code of 1
 


My guess is that this has something to do with Python 3.x not having
raw_input.  Try changing the raw_input calls to input.  I don't get that
error with 2.7.




  If you're talking about re-entering all your data from your file, you
 would
  write a script to do that.

 Ha! I would?


Well, yeah.


A line in the file always begins with a name, with  at
 least one phone number, then if a company, the hours they are
 reachable by phone, possibly their web address, maybe an email
 address, my contact there plus maybe her secretary. If a physician,
 there might very well be his specialty, his nurse's name, mention of
 who recommended him to me, etc.


Like I said, I'd have to see the file to comment more, but it sounds like it
may be too irregular to make writing a script an easy process.  Though I
can't be sure without seeing it.  You could always enter these things by
hand...

I should probably ask; what is your goal for this app?  Is it to learn some
Python while making a usable app?  Or are you looking for a robust address
book for quick lookups of information?  If it's the latter, I'd recommend
you look around for something that's already made.  It will save you a lot
of trouble in the long run.

If you're looking for a good learning experience this kind of app is a great
starting place.  However expect to run into problems along the way, up to
and possibly beyond possibly hosing all the data you have entered into the
app.  Make regular backups of the data and keep your original around.


 It seems that the format of info for
 your way is set rigidly in advance, or am I wrong?


Not really.  Key/value pairs can be entered in arbitrary order.  I used = to
seperate key/values because that's what you used in your app and | to
seperate k/v pairs to allow spaces without quoting strings.  You could
easily replace these tokens (= or |) with whatever you want.

If you have another format that differs by more than those characters you
would need to write a different parser.  However there does have to be some
consistency to the format of your data to make parsing easier.  The less
rigid your data the more work you will have to do to parse it.  Since you
said earlier that you will probably have less than 100 entries in your phone
book, you may want to think about restructuring your data by hand to make it
easier to parse before writing your parser.

-- 
Nick Zarczynski
Pointless Programming Blog http://pointlessprogramming.wordpress.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-08 Thread Richard D. Moores
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@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-08 Thread Christian Witts

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

//
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-08 Thread Richard D. Moores
On Thu, Sep 8, 2011 at 04:36, Christian Witts cwi...@compuscan.co.za wrote:
 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@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

I should have stated that I'm using Win 7, Python 3.2.1. No Unix.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-08 Thread Peter Otten
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.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-08 Thread Steven D'Aprano

Richard D. Moores wrote:


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.


If you expect human beings (yourself, or possibly even the user) to edit 
the text file, then you should look at a human-writable format like these:



Good ol' fashioned Windows INI files:
import configparser
JSON:  import json
PLIST: import plistlib
YAML:  download from http://pyyaml.org/wiki/PyYAML


If the ability to edit the files isn't important, then I suggest using 
the pickle module instead.






--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-08 Thread Richard D. Moores
On Thu, Sep 8, 2011 at 04:43, Peter Otten __pete...@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
eventually.

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.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-08 Thread Richard D. Moores
On Thu, Sep 8, 2011 at 04:43, Peter Otten __pete...@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
eventually.

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.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-08 Thread Alan Gauld

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/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


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

2011-09-08 Thread James Reynolds
On Thu, Sep 8, 2011 at 10:03 AM, Alan Gauld alan.ga...@btinternet.comwrote:

 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/


 __**_
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/**mailman/listinfo/tutorhttp://mail.python.org/mailman/listinfo/tutor




Another option would be for you to use XML and base it off of a schema.

There's a really nifty tool called generate DS (just google it) that will
turn any valid schema into a python module.

I pasted an example schema that you might use here:
http://pastebin.com/AVgVGpgu

 Once you install generateds, just cd to where it is installed and type:
python generateds.py -o pn.py PhoneNumber.xsd

This assumes you named the above schema as PhoneNumber.xsd

That will create a file called pn.py. For some reason it generated a bad
line on line 452, which I just commented out.

I then made a script in just a few lines to make a phonebook:

http://pastebin.com/h4JB0MkZ

This outputs XML that looks like this:

PhoneBook
 Listing
 PersonsNameaaa/PersonsName
 Number Type=Mobile
 Number1231231234/Number
 /Number
 /Listing
 Listing
 PersonsNamebbb/PersonsName
 Number Type=Work
 Number1231231234/Number
 /Number
 Number Type=Home
 Number6789231234/Number
 /Number
 /Listing
 Listing
 PersonsNameccc/PersonsName
 Number Type=Fax
 Number1231231234/Number
 /Number
 /Listing
 Listing
 PersonsNameddd/PersonsName
 Number Type=Home
 Number1231231234/Number
 /Number
 /Listing
 /PhoneBook


The advantage is, you can immediately grab the generated xml and create
python instances using the build() method for further editing. You would of
course need to create a schema that fits your needs. Mine was just a quick
and dirty example of what you could do.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor