My Big Dict.

Attila Bleier ableier at axelero.hu
Wed Jul 2 13:45:12 EDT 2003


"drs" <drs at ecp.cc> wrote in message news:<TXvMa.9902$BM.3065756 at newssrv26.news.prodigy.com>...
> "Christophe Delord" <christophe.delord at free.fr> wrote in message
> news:20030702073735.40293ba2.christophe.delord at free.fr...
> > Hello,
> >
> > On Wed, 2 Jul 2003 00:13:26 -0400, Xavier wrote:
> >
> > > Greetings,
> > >
> > > (do excuse the possibly comical subject text)
> > >
> > > I need advice on how I can convert a text db into a dict.  Here is an
> > > example of what I need done.
> > >
> > > some example data lines in the text db goes as follows:
> > >
> > > CODE1!DATA1 DATA2, DATA3
> > > CODE2!DATA1, DATA2 DATA3
> > >
> > > As you can see, the lines are dynamic and the data are not alike, they
> > > change in permission values (but that's obvious in any similar
> > > situation)
> > >
> > > Any idea on how I can convert 20,000+ lines of the above into the
> > > following protocol for use in my code?:
> > >
> > > TXTDB = {'CODE1': 'DATA1 DATA2, DATA3', 'CODE2': 'DATA1, DATA2 DATA3'}
> > >
> >
> > If your data is in a string you can use a regular expression to parse
> > each line, then the findall method returns a list of tuples containing
> > the key and the value of each item. Finally the dict class can turn this
> > list into a dict. For example:
> 
> and you can kill a fly with a sledgehammer.  why not
> 
> f = open('somefile.txt')
> d = {}
> l = f.readlines()
> for i in l:
>     a,b = i.split('!')
>     d[a] = b.strip()
> 
> or am i missing something obvious? (b/t/w the above parsed 20000+ lines on a
> celeron 500 in less than a second.)
> 
> -d
Just a short notice, l=f.readlines() line is not needed at all. It is
a bit more comprehensive to write for i in f.readlines(): instead - as
l is not used elsewhere - it is only  memory wasting.Not a big deal,
but it is worth noticing. Using regexp to justify the line length, and
# of exlamation marks etc - is not needed in most cases, I think - it
is easier and faster to put the whole stuff into a try : except
clause. I admit though that there are cases in which they might come
in handy - in this case though, it seems to be an overkill.
Attila




More information about the Python-list mailing list