日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/4/5 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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:更新深度嵌套字典中的值的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。