Python:将函数应用于嵌套字典中的值 [英] Python: Apply function to values in nested dictionary
问题描述
我有一组任意深的嵌套字典:
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}}
我想基本上将一个函数应用于字典中的所有整数,所以我想像map
一样,但是对于嵌套字典.
and I'd like to basically apply a function to all the integers in the dictionaries, so like map
, I guess, but for nested dictionaries.
所以:map_nested_dicts(x, lambda v: v + 7)
是目标.
我坚持最好的方法来存储键层,然后将修改后的值放回正确的位置.
I'm stuck as to the best way to perhaps store the layers of keys to then put the modified value back into its correct position.
做到这一点的最佳方法/方法是什么?
What would the best way/approach to do this be?
推荐答案
以递归方式访问所有嵌套值:
Visit all nested values recursively:
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}}
在某些情况下,希望修改原始字典对象(以避免重新创建):
In some cases it's desired to modify the original dict object (to avoid re-creating it):
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}}
如果您使用的是Python 3:
If you're using Python 3:
-
将
dict.iteritems
替换为dict.items
将import collections
替换为import collections.abc
将collections.Mapping
替换为collections.abc.Mapping
这篇关于Python:将函数应用于嵌套字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!