Skip to content

Instantly share code, notes, and snippets.

@fudomunro
Created March 9, 2012 14:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fudomunro/2006829 to your computer and use it in GitHub Desktop.
Save fudomunro/2006829 to your computer and use it in GitHub Desktop.
Recursively format a dictionary of strings
def dict_format(original, **kwargs):
"""Recursively format the values in *original* with *kwargs*.
>>> sample = {"key": "{value}", "sub-dict": {"sub-key": "sub-{value}"}}
>>> dict_format(sample, value="Bob") == \
{'key': 'Bob', 'sub-dict': {'sub-key': 'sub-Bob'}}
True
"""
new = {}
for key, value in original.items():
if type(value) == type({}):
new[key] = dict_format(value, **kwargs)
elif type(value) == type(""):
new[key] = value.format(**kwargs)
else:
new[key] = value
return new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment