CONTEST - What is the (best) solution?

Steven Bethard steven.bethard at gmail.com
Wed Feb 2 15:09:11 EST 2005


python at hope.cz wrote:
> In a file there can be several dictionaries like this
> {Key11: Value11
> Key12: Value12
> Key13: Value13,
> ...
> ...
> Key1n:Value1n}
> {Key21: Value21
> Key22: Value22
> Key23: Value23,
> ...
> ...
> Key2n:Value2n}
> {Key31: Value31
> Key32: Value32
> Key33: Value33,
> ...
> ...
> Key3n:Value3n}
> ....
> ....
> ....
> {Keyn1: Valuen1
> Keyn2: Valuen2
> Keyn3: Value3,
> ...
> ...
> Keynn:Valuenn}
> 
> Each pair in a dictionary is separated by CRLF and in each dictionary
> numbers of pairs can be different.
> I need to read only the the first and the last dictionaries.What is a
> best solution?

Assumption:
File is small enough to be read into memory at once.  Contents of the 
file have been read into the variable "testdata":

py> # your data
py> testdata="""
... {Key11: Value11
... Key12: Value12,
... Key13: Value13}
... {Key21: Value21,
... Key22: Value22
... Key23: Value23}
... {Key31: Value31
... Key32: Value32,
... Key33: Value33}
... """
py>
py> # get the contents of the first and last dict
py> content_strs = testdata.strip('{}\n\t ').split('}\n{')
py> content_strs = content_strs[0], content_strs[1]
py> print content_strs
('Key11: Value11\nKey12: Value12,\nKey13: Value13', 'Key21: 
Value21,\nKey22: Value22\nKey23: Value23')
py>
py> # correct missing commas and add braces
py> dict_strs = ['{%s}' % s.replace('\n', ',\n').replace(',,\n', ',\n')
...              for s in content_strs]
py> print dict_strs
['{Key11: Value11,\nKey12: Value12,\nKey13: Value13}', '{Key21: 
Value21,\nKey22: Value22,\nKey23: Value23}']
py>
py> # build mapping of names to values
py> names = {}
py> for i in range(1, 4):
...     for j in range(1, 4):
...         s = '%i%i' % (i, j)
...         names['Key%s' % s] = int(s)
...         names['Value%s' % s] = 'V%s' % s
...
py>
py> # eval strings to get dicts
py> first_dict, last_dict = [eval(s, names) for s in dict_strs]
py> first_dict
{11: 'V11', 12: 'V12', 13: 'V13'}
py> last_dict
{21: 'V21', 22: 'V22', 23: 'V23'}



More information about the Python-list mailing list