Skip to content

Instantly share code, notes, and snippets.

@kgourgou
Created November 21, 2017 12:47
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 kgourgou/72df7cfedced19356b6912ba399e356f to your computer and use it in GitHub Desktop.
Save kgourgou/72df7cfedced19356b6912ba399e356f to your computer and use it in GitHub Desktop.
from scipy import clip
def dict_clipper(dictionary):
"""
Clips all the numeric values of a dictionary so
that they lie within [0,1].
It recurses within inner dictionaries,
if any.
>>> A = {"B":-5, "C":{"D":10000, "F":0.3}}
>>> dict_clipper(A)
>>> print(A)
{"B":0, "C":{"D":1, "F":0.3}}
"""
for key in dictionary:
if isinstance(dictionary[key], numbers.Number):
dictionary[key] = clip(dictionary[key], 0, 1)
elif isinstance(dictionary[key], dict):
dict_clipper(dictionary[key])
else:
raise ValueError(f"Cannot recognise dictionary[{key}]")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment