I have to work with a nested dictionary filled with numbers in python 'my_dict', and a list that specifies the subkeys 'keys 'that have to be deleted:
keys=[1,9]
my_dict={1:{1:a, 2:b}, 2:{1:c, 3:d, 9:e}}
I want to have two outcomes:
Delete all subkeys+their values if they are in keys, e.g.
new_dict={1:{2:b}, 2:{3:d}}
Or Delete all subkeys+their values if they are not in keys, e.g.
new_dict:{1:{1:a}, 2:{1:c,9:e}}
I have tried:
new_list = {outer_k: {inner_k: inner_v for inner_k, inner_v in outer_v.items()-{1,9}} for outer_k, outer_v in my_dict.items()}
It gives me back the same dict without deletion of the elements, same for the second szenario
new_list = {outer_k: {inner_k: inner_v for inner_k, inner_v in outer_v.items()&{1,9}} for outer_k, outer_v in my_dict.items()}
I have also tried:
for key, value in my_dict.items():
for key1, value1 in value.items():
for key1 in keys:
try:
del dict[key1]
except KeyError:
pass
This gives me the error:
TypeError: 'type' object does not support item deletion
I would be glad if anyone knows of a neat solution for this!