String formatting with nested dictionaries

Fredrik Lundh fredrik at pythonware.com
Thu Aug 24 15:02:51 EDT 2006


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.

the % operator treats the keys as plain keys, not expressions.  if you 
trust the template provider, you can use a custom wrapper to evaluate 
the key expressions:

mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar', 
'Hammer':'nails'}

class wrapper:
     def __init__(self, dict):
	self.dict = dict
     def __getitem__(self, key):
	try:
	    return self.dict[key]
	except KeyError:
	    return eval(key, self.dict)

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" % wrapper(mydict)

foo is set to bar - Value One is: 1 and Value Two is: 2 -- Hammers are 
used to pound in nails

</F>




More information about the Python-list mailing list