我有一本看起來像的字典:
my_dict = {
'A': 'update_me',
'B': {
'C': 'D',
'E': 'F'
},
'G': {
'H': 'update_me',
'I': 'J',
'K': 'update_me'
}
}
我正在嘗試創建一個函式,該函式將遍歷每個鍵值對并確定該值是否為update_me. 如果是,它將將該值設定為等于this_worked。所以它看起來像這樣:
my_dict = {
'A': 'this_worked',
'B': {
'C': 'D',
'E': 'F'
},
'G': {
'H': 'this_worked',
'I': 'J',
'K': 'this_worked'
}
}
除此之外,我希望它是動態的,這樣代碼就不必顯式查找my_dict['A']ormy_dict['G']['H']。它應該回圈遍歷每個鍵值對,如果該值是update_me,則更新它(我還有其他字典需要以類似方式更新,但它們的鍵、長度和深度各不相同)。
我想我真的只需要一種方法來遍歷具有任意數量特定級別的字典的每個級別。
uj5u.com熱心網友回復:
處理具有任意嵌套級別的操作的一種簡單方法是遞回函式。在這種情況下,您希望對字典中的每個專案執行操作,并對每個本身就是字典的專案執行相同的操作:
>>> def recursive_replace(d, old, new):
... if d == old:
... return new
... if not isinstance(d, dict):
... return d
... return {k: recursive_replace(v, old, new) for k, v in d.items()}
...
>>> recursive_replace(my_dict, "update_me", "this_worked")
{'A': 'this_worked', 'B': {'C': 'D', 'E': 'F'}, 'G': {'H': 'this_worked', 'I': 'J', 'K': 'this_worked'}}
uj5u.com熱心網友回復:
一個解決方案可能是:
def replace(my_dict, old_test="update_me", new_text="this_worked"):
for x, y in my_dict.items():
if type(y) is dict:
replace(y)
elif type(y) is str:
if y == old_text:
y = new_text
my_dict[x] = y
return my_dict
uj5u.com熱心網友回復:
你可以通過這個實作
my_dict = {
'A': 'update_me',
'B': {
'C': 'D',
'E': 'F'
},
'G': {
'H': 'update_me',
'I': 'J',
'K': 'update_me'
}
}
old_value = "update_me"
new_value = "new_value"
def replace_value(my_dict, old_value, new_value):
for key, value in my_dict.items():
if type(value) is dict:
replace_value(value, old_value, new_value)
elif value == old_value:
my_dict[key] = new_value
return my_dict
my_dict = replace_value(my_dict, old_value, new_value)
print(my_dict)
# {'A': 'new_value', 'B': {'C': 'D', 'E': 'F'}, 'G': {'H': 'new_value', 'I': 'J', 'K': 'new_value'}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404567.html
標籤:
下一篇:基于一鍵匹配值合并字典串列
