extract to dictionaries

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Thu May 28 19:59:57 EDT 2009


Marius Retegan:
>
> parameters1
>      key1 value1
>      key2 value2
> end
>
> parameters2
>      key1 value1
>      key2 value2
> end
>
> So I want to create two dictionaries parameters1={key1:value1,
> key2:value2} and the same for parameters2.

I have wasted some time trying to create a regex for that. But it's
better to use normal code. Iterate on the lines, keep a dict, and when
you find a string that doesn't start with whitespace, use it to create
a new key-value into the dict, where the key is the stripped line and
the value is an empty dict. Then you can enter a sub loop or set a
"inside" boolean variable, to denote you are in a different part of
the state machine. When you find lines that start with a space, you
can put add them as key-value into the latest dict (so you have to
keep the key name in the superdict, or more efficiently you can keep
your subdict on a side, and you can add it only at the end when you
see a line "end" with no leading spaces. When you find such "end" you
can exit the sub loop or rest the "inside" boolean.
Overall if's just few lines of code, much shorter than my description
of the algorithm.

Bye,
bearophile



More information about the Python-list mailing list