Created
November 7, 2018 22:08
-
-
Save beatorizu/ac5eedd88243f9e65a00f4e00e78506c to your computer and use it in GitHub Desktop.
Convert values in nested dicts using python
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
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