亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

刪除嵌套字典中任意深度的鍵

刪除嵌套字典中任意深度的鍵

不負相思意 2023-07-27 16:23:42
我的目標是從嵌套字典中刪除一個值。假設我有字典: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]]


查看完整回答
反對 回復 2023-07-27
  • 1 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號