Naming dictionaries recursively

Paul McGuire ptmcg at austin.rr.com
Fri Aug 17 10:53:20 EDT 2007


On Aug 17, 7:38 am, TYR <a.harrow... at gmail.com> wrote:
> I'd like to do something like this; iterate through a file which
> consists of data stored in dictionary format, one dict on each line,
> and read each line into a new dict using one of the values in the dict
> as its name...
>
> for example:
>
> stuff = open('data.txt')
>  for eachLine in stuff:
>   name{}
>    name = eachLine
> ....and then do something clever to extract the value of the key
> (name) from the line and use it as the dictionary's name.
>
> A line from data.txt would look like this: {'name' : Bob, 'species' :
> Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of
> them by name, and merge the values in that dictionary into a string
> pulled from another source.

Pyparsing includes an example that is very similar to this.  Here is
that example adapted to your specific data:

from pyparsing import *

line = """{'name' : Bob, 'species' : Humboldt, 'colour' : red,
'habits' : predatory}"""

LBRACE,RBRACE,COLON,COMMA = map(Suppress,"{}:,")
key = sglQuotedString.setParseAction(removeQuotes)
value = OneOrMore(Word(alphanums))\
                    .setParseAction(keepOriginalText)
entry = Group(key + COLON + empty + value)
lineExpr = LBRACE + Dict(delimitedList(entry)) + RBRACE

parsedData = lineExpr.parseString(line)

# some examples of accessing the parsed data
print "Keys:", parsedData.keys()
print parsedData.name
print parsedData.colour
print "Name: %(name)s \nSpecies: %(species)s \n" \
        "Colour: %(colour)s \nHabits: %(habits)s" % parsedData

Prints:

Keys: ['colour', 'habits', 'name', 'species']
Bob
red
Name: Bob
Species: Humboldt
Colour: red
Habits: predatory

-- Paul




More information about the Python-list mailing list