[Tutor] Converting a txt file to dictionary

Peter Otten __peter__ at web.de
Wed Aug 26 13:29:23 EDT 2020


nzbz xx wrote:

Interesting name ;)

> I have a plantrecords.txt file with the following format:
> 
> Plantname
> date & time of record
> description
> description
> description
> (blank line)
> Plantname
> date & time of record
> description
> description
> description
> (blank line)
> .
> .
> .
> 
> 
> How do I  convert this text file into a dictionary such that it gives me
> dict = {'plantname': [datetimerecord, description, description,
> description], 'plantname': [datetime.....]} so on and so forth


import itertools
import pprint

filename = "plants.txt"
plants = {}
with open(filename) as instream:
    for key, group in itertools.groupby(map(str.strip, instream), key=bool):
        if key:
            name, *rest = group
            plants[name] = rest

pprint.pprint(plants)




More information about the Tutor mailing list