Skip to content

Instantly share code, notes, and snippets.

@burnto
Created April 6, 2012 17:55
Show Gist options
  • Save burnto/2321643 to your computer and use it in GitHub Desktop.
Save burnto/2321643 to your computer and use it in GitHub Desktop.
A nasty deep dictionary apply utility
def deep_dict_apply(d, k_fn=None, v_fn=None):
"""
>>> def k_fn(key):
... return str(key) + "_k"
>>> def v_fn(value):
... return str(value) + "_v"
>>> dictionary = {1: {2: {3: 'hello'}}, 4: 'world'}
>>> deep_dict_apply(dictionary, k_fn, v_fn)
{'4_k': 'world_v', '1_k': {'2_k': {'3_k': 'hello_v'}}}
>>> deep_dict_apply(dictionary, k_fn)
{'4_k': 'world', '1_k': {'2_k': {'3_k': 'hello'}}}
>>> deep_dict_apply(dictionary, v_fn=v_fn)
{1: {2: {3: 'hello_v'}}, 4: 'world_v'}
"""
return dict([(k_fn and k_fn(k) or k, isinstance(v, dict) and deep_dict_apply(v, k_fn, v_fn) or v_fn and v_fn(v) or v) for k, v in d.items()])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment