String formatting with nested dictionaries

Diez B. Roggisch deets at nospam.web.de
Thu Aug 24 12:43:20 EDT 2006


linnorm at gmail.com schrieb:
> 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've looked through the docs and google and can't find anything
> relating to this.

Because it is not supported. You can only use one level of keys, and it 
must be strings. So you have to do it like this:


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 
poundin %(Hammer)s" % dict(Hammer=mydict['Hammer'], 
Value1=mydict["inner_dict"]["Value1"], 
Value2=mydict["inner_dict"]["Value2"])


Diez




More information about the Python-list mailing list