python嵌套字典赋值_Python:更新深度嵌套字典中的值

选择的答案肯定是正确的。我(稍后)发现的问题是我的嵌套键可能出现在不同的级别。所以我需要能够遍历dict并首先找到节点的路径,然后进行更新或添加。在

jsonpath\u-rw是最直接的解决方案,但我尝试使用它时得到了一些奇怪的结果。经过几个小时的努力,我放弃了。在

冒着因笨手笨脚而遭到批评的风险,我最终还是充实了一些函数(基于我在SO上找到的其他代码),这些函数本机地做了一些很好的事情来满足我的需求:def find_in_obj(obj, condition, path=None):

''' generator finds full path to nested dict key when key is at an unknown level

borrowed from http://stackoverflow.com/a/31625583/5456148'''

if path is None:

path = []

# In case this is a list

if isinstance(obj, list):

for index, value in enumerate(obj):

new_path = list(path)

new_path.append(index)

for result in find_in_obj(value, condition, path=new_path):

yield result

# In case this is a dictionary

if isinstance(obj, dict):

for key, value in obj.items():

new_path = list(path)

new_path.append(key)

for result in find_in_obj(value, condition, path=new_path):

yield result

if condition == key:

new_path = list(path)

new_path.append(key)

yield new_path

def set_nested_value(nested_dict, path_list, key, value):

''' add or update a value in a nested dict using passed list as path

borrowed from http://stackoverflow.com/a/11918901/5456148'''

cur = nested_dict

path_list.append(key)

for path_item in path_list[:-1]:

try:

cur = cur[path_item]

except KeyError:

cur = cur[path_item] = {}

cur[path_list[-1]] = value

return nested_dict

def update_nested_dict(nested_dict, findkey, updatekey, updateval):

''' finds and updates values in nested dicts with find_in_dict(), set_nested_value()'''

return set_nested_value(

nested_dict,

list(find_in_obj(nested_dict, findkey))[0],

updatekey,

updateval

)

find_in_obj()是一个生成器,用于查找指向给定嵌套键的路径。在

set_nested_values()将使用给定列表更新dict中的键/值,如果不存在,则将其添加到中。在

update_nested_dict()是接受嵌套dict进行搜索的两个函数的“包装器”,即要搜索的键和要更新的键值(如果不存在,则添加)。在

所以我可以进去:

^{pr2}$

“operator”值会更新,“minimum_should_match”键/值将添加到“multi_match”节点下,而不管它出现在字典中的哪个级别。在

但是,如果搜索的关键字存在于字典中的多个位置,则可能会遇到问题。在

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值