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. :)
Thanks. It can be useful.
ReplyDeleteBtw, you can replace type({}) with types.DictionaryType and type("") with types.StringType.
Thanks Alexander. I knew there was a simpler way to reference those basic types, but I always forget it at code time. :)
ReplyDeleteHeya¡my very first comment on your site. ,I have been reading your blog for a while and thought I would completely pop in
ReplyDeleteAppear fervent about it. I’m developing a fresh blog plus I’m struggling to make it look good, as well as offer the best
quality content. I have learned much at your web site and also I anticipate alot more articles and will be coming back
soon. Thanks you.
Journal Editing and Formatting Service