writing from file into dictionary
Brad Hards
bhards at bigpond.net.au
Mon Nov 11 07:15:03 EST 2002
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Mon, 11 Nov 2002 22:16, Alex Martelli wrote:
<snip>
> Assuming the trailing colon at the end of the 'rewrite' part
> (and anything following it, such as the comment in the last
> line) is to be removed; and that corresponding to each head
> you want a list of the possible rewrites for that head;
>
Can I try an explanation?
> grammardict = {}
This creates a dictionary, and provides a references that dictionary, which is
"grammardict". We'll need this later.
> for line in open('thefile'):
open() is another name for file() in 2.2
When used this way, open() or file(), takes a default of opening in read only
mode, with unbuffered I/O.
open() returns a file object, which the for loop iterates over. This magic
iteration only works on later versions of python (ie not 1.5.2 :). When and
if the iteration does work, the name "line" refers to each line in the file.
> head, rewrite = line.split(':',2)[:2]
"line.split(':'.2)" means to create a list of up to three items from the text
referenced by "line", by taking all the characters up to the delimiting colon
(":"). We need a list of three items to avoid the second colon being attached
to the second item.
Having got our list of three items, we create a slice consisting of the first
two items. This sliced list is then unpacked into two variables - "head" and
"rewrite". You could also use:
head, rewrite = filter(None, line.split(':',2))
but I guess that is less efficient, otherwise Alex would have used it.
> grammardict.setdefault(head, []).append(rewrite)
This searches the dictionary refered to by "grammarlist" for an list that is
keyed by a string equal to "head", creating an empty list entry if it doesn't
already exist. The "append" part then operates on the string referred to by
the "rewrite" variable, adding it to the (possibly empty) list keyed by
"head".
To rephrase:
If grammardict does not include any entry keyed by "head", then an entry is
created, consisting of an empty list. "rewrite" is then appended to that
empty list, creating a dictionary entry of head:[rewrite].
If grammardict does include an entry keyed by "head", then "rewrite" is
appended to the existing list, resulting in a dictionary entry of head: [
existing, rewrite].
How close is this?
Brad
- --
http://linux.conf.au. 22-25Jan2003. Perth, Aust. I'm registered. Are you?
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org
iD8DBQE9z59HW6pHgIdAuOMRAsPMAJsETGh5RGjVp9lbtX3RTkK5QVXLhgCgsiof
kWWytJjUfX9+zABxVmHImvw=
=lAOz
-----END PGP SIGNATURE-----
More information about the Python-list
mailing list