writing from file into dictionary

Alex Martelli aleax at aleax.it
Mon Nov 11 06:16:11 EST 2002


Bo wrote:

> Hi all!
> I've just started to "play" with Python. Can someone tell me how to
> read the grammar in from the file , and place it into a dictionary ?
> The grammar is represented by lines where the head is separated from
> the rewrite by a colon, as in the following :
> 
> start:person does something:
> start:I do something:
> activity:dancing:
> activity:eating:  #and more
> 
> This should be placed into a dictionary...
> Thanks a lot, greetings
> Bo

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;

grammardict = {}
for line in open('thefile'):
    head, rewrite = line.split(':',2)[:2]
    grammardict.setdefault(head, []).append(rewrite)


Alex




More information about the Python-list mailing list