0

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?

ex-zac-tly
  • 979
  • 1
  • 8
  • 24
  • 2
    suggestions: don't remove items, build a new dict; and simply recursively traverse the `dataDict`. Coding efforts from the question asker are appreicated – Chris_Rands Apr 26 '18 at 13:40
  • I am not able to understand exact problem. Can you write expected result? – Harshad Kavathiya Apr 26 '18 at 13:40
  • Did an answer below help? Feel free to accept an answer (green tick on left), or ask for clarification. – jpp May 08 '18 at 11:16

4 Answers4

2

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]]
jpp
  • 159,742
  • 34
  • 281
  • 339
0

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
    }
}
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • This works for a list of length 3, but will not work for arbitrary length lists. Relevant given dictionary structure. – jpp Apr 26 '18 at 13:44
0
for k in maplist:
    if k in dataDict:
        del dataDict[k]

Output:

{'a': {'s': 2, 'r': 1, 't': 3}}
NoorJafri
  • 1,787
  • 16
  • 27
0

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}}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102