选择的答案肯定是正确的。我(稍后)发现的问题是我的嵌套键可能出现在不同的级别。所以我需要能够遍历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”节点下,而不管它出现在字典中的哪个级别。在
但是,如果搜索的关键字存在于字典中的多个位置,则可能会遇到问题。在