From 54e1a4b74eace21b3af4f691c7ad202d456bbb85 Mon Sep 17 00:00:00 2001 From: Robert Izzard <r.izzard@surrey.ac.uk> Date: Fri, 22 Oct 2021 12:26:05 +0100 Subject: [PATCH] add function to multiply float values in a nested dict --- binarycpython/utils/functions.py | 53 ++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/binarycpython/utils/functions.py b/binarycpython/utils/functions.py index ed5e37108..bf5d4cf2f 100644 --- a/binarycpython/utils/functions.py +++ b/binarycpython/utils/functions.py @@ -2442,3 +2442,56 @@ def ensemble_setting(ensemble,parameter_name): value = None return value + +############################################################ +# code to walk a dictionary recursively based on +# https://stackoverflow.com/questions/13687924/setting-a-value-in-a-nested-python-dictionary-given-a-list-of-indices-and-value +def _nested_set(dic, keys, value): + for key in keys[:-1]: + dic = dic.setdefault(key, {}) + dic[keys[-1]] = value +def _nested_get(dic, keys): + for key in keys[:-1]: + dic = dic.setdefault(key, {}) + return dic[keys[-1]] + +# function to walk through the dictionary, multiplying +# float values by const +def _recursive_normalize_floats(path,d,const,parent=None): + if not parent: + parent = d + for k,v in d.items(): + if isinstance(v,float): + path.append(k) + # must be a float, multiply by the constant + _nested_set(parent,path,v * const) + path.pop() + elif isinstance(v, str) or isinstance(v, int): + path.append(k) + # do nothing to strings or ints + path.pop() + elif v is None: + path.append(k) + path.pop() + # dicts + # note: isinstance isn't enough, we need to check the Mapping + elif isinstance(v,collections.abc.Mapping): + path.append(k) + # nested dict + _recursive_normalize_floats(path,v,const,parent=parent) + path.pop() + else: + print ("###Type {} not recognized: {}.{}={}".format(type(v), ".".join(path),k, v)) + +def multiply_float_values(d,const): + """ + multiply_float_values : A function to recursively multiply values of a (nested) dictionary that are floats by a constant. Nested dictionaries call this function recursively. + + Args: + d = the dictionary + const = the constant that multiplies float values + """ + path=[] + _recursive_normalize_floats(path,d,const,parent=d) + +############################################################ -- GitLab