Skip to content

Instantly share code, notes, and snippets.

@beatorizu
Created November 7, 2018 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beatorizu/ac5eedd88243f9e65a00f4e00e78506c to your computer and use it in GitHub Desktop.
Save beatorizu/ac5eedd88243f9e65a00f4e00e78506c to your computer and use it in GitHub Desktop.
Convert values in nested dicts using python
from collections.abc import Mapping
# Recursive function to apply a func to nested dict
def map_nested_dicts(ob, func):
if isinstance(ob, Mapping):
return {key: map_nested_dicts(value, func) for key, value in ob.items()}
return func(ob)
# Convert items of a list to type
def totype(values, type):
try:
return list(map(type, values))
except ValueError:
return values
# Curried func
def toint(values):
return totype(values, int)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment