递归访问字典和修改

递归访问字典和修改,第1张

递归访问字典和修改

您可以使用该

reduce()
函数遍历一系列嵌套字典:

def get_nested(d, path):    return reduce(dict.__getitem__, path, d)

演示:

>>> def get_nested(d, path):...     return reduce(dict.__getitem__, path, d)... >>> my_dict = {'key1': {'key2': {'foo': 'bar', 'key3': {'key4': {'key5': 'blah'}}}}}>>> get_nested(my_dict, ('key1', 'key2', 'key3', 'key4', 'key5'))'blah'

当密钥不存在时,此版本引发异常:

>>> get_nested(my_dict, ('key1', 'nonesuch'))Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 2, in get_nestedKeyError: 'nonesuch'

但您可以替换

dict.__getitem__
lambda d, k: d.setdefault(k, {})
,使其创建空字典:

def get_nested_default(d, path):    return reduce(lambda d, k: d.setdefault(k, {}), path, d)

演示:

>>> def get_nested_default(d, path):...     return reduce(lambda d, k: d.setdefault(k, {}), path, d)... >>> get_nested_default(my_dict, ('key1', 'nonesuch')){}>>> my_dict{'key1': {'key2': {'key3': {'key4': {'key5': 'blah'}}, 'foo': 'bar'}, 'nonesuch': {}}}

要在给定路径上 设置 值,请遍历除最后一个键以外的所有键,然后在常规词典分配中使用最后一个键:

def set_nested(d, path, value):    get_nested_default(d, path[:-1])[path[-1]] = value

这使用该

get_nested_default()
函数根据需要添加空字典:

>>> def set_nested(d, path, value):...     get_nested_default(d, path[:-1])[path[-1]] = value... >>> my_dict = {'key1': {'key2': {'foo': 'bar'}}}>>> set_nested(my_dict, ('key1', 'key2', 'key3', 'key4', 'key5'), 'blah')>>> my_dict{'key1': {'key2': {'key3': {'key4': {'key5': 'blah'}}, 'foo': 'bar'}}}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5645538.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存