如何用列表作为键路径访问嵌套字典并进行增删操作?
解决嵌套字典的动态键路径访问与修改问题
给定嵌套字典和包含键路径的动态列表,我们可以通过以下方式实现对应值的获取,以及对最终层级键值对的增删操作:
1. 获取指定路径的值
方法一:循环遍历路径
最直观的方式就是逐层遍历列表中的键,深入嵌套字典:
foo = {"/" : {"bar": {"morefoo": "returnme"}} } example = ["/","bar","morefoo"] current = foo for key in example: current = current[key] print(current) # 输出: returnme
方法二:用functools.reduce简化代码
如果偏好简洁写法,可以用reduce函数一次性完成逐层访问:
from functools import reduce foo = {"/" : {"bar": {"morefoo": "returnme"}} } example = ["/","bar","morefoo"] result = reduce(lambda d, k: d[k], example, foo) print(result) # 输出: returnme
2. 对最终层级的键值对进行增删操作
要修改、添加或删除最终层级的内容,需要先定位到倒数第二层的字典,再操作最后一个键:
添加/修改键值对
foo = {"/" : {"bar": {"morefoo": "returnme"}} } example = ["/","bar","newkey"] # 拆分路径:前n-1个键是父路径,最后一个是目标键 parent_keys = example[:-1] target_key = example[-1] # 定位到父字典 parent_dict = foo for key in parent_keys: parent_dict = parent_dict[key] # 添加或修改值 parent_dict[target_key] = "new_value" print(foo) # 输出: {"/": {"bar": {"morefoo": "returnme", "newkey": "new_value"}}}
删除键值对
foo = {"/" : {"bar": {"morefoo": "returnme"}} } example = ["/","bar","morefoo"] parent_keys = example[:-1] target_key = example[-1] parent_dict = foo for key in parent_keys: parent_dict = parent_dict[key] # 删除指定键 del parent_dict[target_key] print(foo) # 输出: {"/": {"bar": {}}}
3. 封装成工具函数(可选)
如果需要多次使用这些逻辑,可以封装成函数,提升复用性:
from functools import reduce def get_nested_value(d, keys): return reduce(lambda d, k: d[k], keys, d) def set_nested_value(d, keys, value): parent_dict = reduce(lambda d, k: d[k], keys[:-1], d) parent_dict[keys[-1]] = value def delete_nested_key(d, keys): parent_dict = reduce(lambda d, k: d[k], keys[:-1], d) del parent_dict[keys[-1]] # 使用示例 foo = {"/" : {"bar": {"morefoo": "returnme"}} } example = ["/","bar","morefoo"] print(get_nested_value(foo, example)) # returnme set_nested_value(foo, ["/","bar","newkey"], "hello") print(foo) # {"/": {"bar": {"morefoo": "returnme", "newkey": "hello"}}} delete_nested_key(foo, example) print(foo) # {"/": {"bar": {"newkey": "hello"}}}
内容的提问来源于stack exchange,提问作者Pressing the buttons
相关产品推荐
相关产品推荐

