Python: Apply function to values in nested dictionary

前端 未结 3 1493
我寻月下人不归
我寻月下人不归 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:07

    If you need it to work for both lists and dicts in arbitrary nesting:

    def apply_recursive(func, obj):
        if isinstance(obj, dict):  # if dict, apply to each key
            return {k: apply_recursive(func, v) for k, v in obj.items()}
        elif isinstance(obj, list):  # if list, apply to each element
            return [apply_recursive(func, elem) for elem in obj]
        else:
            return func(obj)
    

提交回复
热议问题