Python:将函数应用于嵌套字典中的值

Jea*_*Luc 11 python dictionary loops python-2.7

我有一套任意深度的嵌套字典:

x = {'a': 1, 'b': {'c': 6, 'd': 7, 'g': {'h': 3, 'i': 9}}, 'e': {'f': 3}}
Run Code Online (Sandbox Code Playgroud)

我想基本上将一个函数应用于字典中的所有整数,所以map我想,但是对于嵌套字典.

所以:map_nested_dicts(x, lambda v: v + 7)就是那种目标.

我坚持使用最好的方法来存储键层,然后将修改后的值放回正确的位置.

这样做的最佳方式/方法是什么?

vau*_*tah 17

以递归方式访问所有嵌套值:

import collections

def map_nested_dicts(ob, func):
    if isinstance(ob, collections.Mapping):
        return {k: map_nested_dicts(v, func) for k, v in ob.iteritems()}
    else:
        return func(ob)

map_nested_dicts(x, lambda v: v + 7)
# Creates a new dict object:
#    {'a': 8, 'b': {'c': 13, 'g': {'h': 10, 'i': 16}, 'd': 14}, 'e': {'f': 10}}
Run Code Online (Sandbox Code Playgroud)

在某些情况下,需要修改原始的dict对象(以避免重新创建它):

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)
        else:
            ob[k] = func(v)

map_nested_dicts_modify(x, lambda v: v + 7)
# x is now
#    {'a': 8, 'b': {'c': 13, 'g': {'h': 10, 'i': 16}, 'd': 14}, 'e': {'f': 10}}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Python 3:

  • 替换dict.iteritemsdict.items

  • 替换import collectionsimport collections.abc

  • 替换collections.Mappingcollections.abc.Mapping