String formatting with nested dictionaries

linnorm at gmail.com linnorm at gmail.com
Thu Aug 24 13:42:10 EDT 2006


Gabriel Genellina wrote:
> At Thursday 24/8/2006 13:22, linnorm at gmail.com wrote:
>
> >I've got a bit of code which has a dictionary nested within another
> >dictionary.  I'm trying to print out specific values from the inner
> >dict in a formatted string and I'm running into a roadblock.  I can't
> >figure out how to get a value from the inner dict into the string.  To
> >make this even more complicated this is being compiled into a large
> >string including other parts of the outer dict.
> >
> >mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar',
> >'Hammer':'nails'}
> >
> >print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
> >and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound
> >in %(Hammer)s" % mydict
> >
> >The above fails looking for a key named 'inner_dict['Value1']' which
> >doesn't exist.
>
> I can think of two ways:
>
> a) Flatten your dictionary. That is, move the contents of inner_dict
> onto the outer dict:
> mydict.update(mydict['inner_dict'])
> Then use single names for interpolation
>
> b) Do the interpolation in two steps.
>
> template = "foo is set to %(foo)s - Value One is: %(Value1)s
> and Value Two is: %(Value2)s -- Hammers are used to pound
> in %(Hammer)s"
> output = template % mydict['inner_dict']
> output = output % mydict
>
> Both methods assume that the inner dict takes precedence in case of
> name clashes; reverse the order if you want the opposite.
>
>
> Gabriel Genellina
> Softlab SRL
>

Thanks,  I started going with a) only doing it the long way.
(mydict['Value1'] = mydict['inner_dict']['Value1'])  mydict.update() is
*much* simpler and less prone to errors too.




More information about the Python-list mailing list