ex-zac-tly
ex-zac-tly

Reputation: 979

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?

Upvotes: 0

Views: 427

Answers (4)

Ajax1234
Ajax1234

Reputation: 71451

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}}

Upvotes: 0

NoorJafri
NoorJafri

Reputation: 1827

for k in maplist:
    if k in dataDict:
        del dataDict[k]

Output:

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

Upvotes: 0

jpp
jpp

Reputation: 164613

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]]

Upvotes: 2

Joe Iddon
Joe Iddon

Reputation: 20414

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
    }
}

Upvotes: 0

Related Questions