简体   繁体   中英

remove element in nested dict by list of keys

I have a nested dictionary structure like so:

dataDict = {
"a":{
    "r": 1,
    "s": 2,
    "t": 3
    },
"b":{
    "u": 1,
    "v": {
        "x": 1,
        "y": 2,
        "z": 3
    },
    "w": 3
    }
}    

with a list of keys:

maplist = ["b", "v", "y"]

I want to remove the item in the dict that the maplist is pointing to. Any suggestions?

This is one way. In future, please refer to the question where you found this data.

getFromDict function courtesy of @MartijnPieters .

from functools import reduce
import operator

def getFromDict(dataDict, mapList):
    return reduce(operator.getitem, mapList[:-1], dataDict)

maplist = ["b", "v", "y"]

del getFromDict(dataDict, maplist)[maplist[-1]]

Just use del after accessing:

del dataDict[maplist[0]][maplist[1]][maplist[2]]

which gives:

dataDict = {
"a":{
    "r": 1,
    "s": 2,
    "t": 3
    },
"b":{
    "u": 1,
    "v": {
        "x": 1,
        "z": 3
    },
    "w": 3
    }
}
for k in maplist:
    if k in dataDict:
        del dataDict[k]

Output:

{'a': {'s': 2, 'r': 1, 't': 3}}

You can use recursion:

maplist = ["b", "v", "y"]
dataDict = {'a': {'s': 2, 'r': 1, 't': 3}, 'b': {'u': 1, 'w': 3, 'v': {'y': 2, 'x': 1, 'z': 3}}}  
def remove_keys(d):
  return {a:remove_keys(b) if isinstance(b, dict) else b for a, b in d.items() if a not in maplist}

final_result = remove_keys(dataDict)

Output:

{'a': {'s': 2, 'r': 1, 't': 3}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM