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”節點下,而不管它出現在字典中的哪個級別。在
但是,如果搜索的關鍵字存在于字典中的多個位置,則可能會遇到問題。在
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的python嵌套字典赋值_Python:更新深度嵌套字典中的值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pe中怎么打开移动硬盘 如何在PE中打开
- 下一篇: u303l怎么进入u盘启动 U303L如