I wanted a simple way to define replaceable parts of the dictionary. I made a couple of Google searches, didn't find anything on the first page, so I wrote this:
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 |
gist for dict_format.py
I hope it's useful to someone else, or that I find it next time I have this use-case. :)