Created
March 9, 2012 14:51
-
-
Save fudomunro/2006829 to your computer and use it in GitHub Desktop.
Recursively format a dictionary of strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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