我的目標是從嵌套字典中刪除一個值。假設我有字典:d = {'a': {'b': {'c': 10, 'd': 4}}}。我知道我可以這樣做:del d['a']['b']['d']。但我有一個嵌套鍵列表,長度未知。如果我有 list ,我想產生與上面相同的行為['a', 'b', 'd']。問題是我不知道使用上述語法的鍵列表的長度。要使用相同的輸入訪問值,很簡單:def dict_get_path(dict_in: Dict, use_path: List): # Get the value from the dictionary, where (eg) # use_path=['this', 'path', 'deep'] -> dict_in['this']['path']['deep'] for p in use_path: dict_in = dict_in[p] return dict_in但我無法找出任何類似的方法來刪除項目而不重新構建整個字典。
1 回答

飲歌長嘯
TA貢獻1951條經驗 獲得超3個贊
使用相同的循環,但在最后一個鍵之前停止。然后用它從最里面的字典中刪除。
def dict_del_path(dict_in: Dict, use_path: List):
# Loop over all the keys except last
for p in use_path[:-1]:
dict_in = dict_in[p]
# Delete using last key in path
del dict_in[use_path[-1]]
添加回答
舉報
0/150
提交
取消