首页 > 后端开发 > Python教程 > 如何使用键列表在 Python 中高效访问和更新嵌套字典项?

如何使用键列表在 Python 中高效访问和更新嵌套字典项?

DDD
发布: 2024-12-27 02:53:08
原创
523 人浏览过

How Can I Efficiently Access and Update Nested Dictionary Items in Python Using a List of Keys?

使用键列表访问嵌套字典项

访问嵌套字典结构可能是 Python 编程中的常见任务。在这里,我们探索一种比提供的代码更有效的方法,用于使用键列表检索和修改复杂字典中的数据。

使用 reduce() 进行增强遍历

reduce() 函数是一个强大的工具,用于通过应用单个操作来转换值序列。在这种情况下,我们可以使用它来遍历字典结构,将键列表减少为单个值。 operator.getitem 方法用作在每次迭代时检索下一个字典级别的操作。

from functools import reduce  # forward compatibility for Python 3
import operator

def get_from_dict(data_dict, map_list):
    return reduce(operator.getitem, map_list, data_dict)
登录后复制

使用reduce() 和operator.setitem 更新数据

要更新嵌套字典值,我们可以重用get_from_dict来检索父字典并使用operator.setitem方法来设置

def set_in_dict(data_dict, map_list, value):
    get_from_dict(data_dict, map_list[:-1])[map_list[-1]] = value
登录后复制

示例用法

让我们测试我们的代码:

data_dict = {
    "a": {
        "r": 1,
        "s": 2,
        "t": 3
        },
    "b": {
        "u": 1,
        "v": {
            "x": 1,
            "y": 2,
            "z": 3
            },
        "w": 3
        }
    }    

map_list = ["a", "r"]
print(get_from_dict(data_dict, map_list))  # Output: 1

map_list = ["b", "v", "y"]
print(get_from_dict(data_dict, map_list))  # Output: 2

map_list = ["b", "v", "w"]
set_in_dict(data_dict, map_list, 4)
print(data_dict)  # Updated dictionary with "w": 4
登录后复制

这种增强的方法利用了强大的 Python 函数,如 reduce()和operator.getitem高效地执行嵌套字典操作,使您的代码更干净、更高效。

以上是如何使用键列表在 Python 中高效访问和更新嵌套字典项?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板