Python: Apply function to values in nested dictionary

前端 未结 3 1468
我寻月下人不归
我寻月下人不归 2021-02-20 06:47

I have an arbitrarily deep set of nested dictionary:

x = {\'a\': 1, \'b\': {\'c\': 6, \'d\': 7, \'g\': {\'h\': 3, \'i\': 9}}, \'e\': {\'f\': 3}}
<
3条回答
  •  长情又很酷
    2021-02-20 07:17

    Just to expand on vaultah's answer, if one of your elements can be a list, and you'd like to handle those too:

    import collections
    
    def map_nested_dicts_modify(ob, func):
    for k, v in ob.iteritems():
        if isinstance(v, collections.Mapping):
            map_nested_dicts_modify(v, func)
        elif isinstance(v, list):
            ob[k] = map(func, v)
        else:
            ob[k] = func(v)
    

提交回复
热议问题