栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

递归访问字典和修改

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

递归访问字典和修改

您可以使用该

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'}}}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639731.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号