I have a dictonary that looks something like this:
{
'key1':
{
'a': 'key1',
'b': 'val1',
'c': 'val2'
},
'key2':
{
'a': 'key2',
'b': 'val3',
'c': 'val4'
},
'key3':
{
'a': 'key3',
'b': 'val5',
'c': 'val6'
}
}
I trying to delete the elements in the nested dict based on the key "a" to get an output like this:
{
'key1':
{
'b': 'val1',
'c': 'val2'
},
'key2':
{
'b': 'val3',
'c': 'val4'
},
'key3':
{
'b': 'val5',
'c': 'val6'
}
}
I wrote the following snippet for it:
for k in dict_to_be_deleted:
del k["a"]
I keep getting Key Error: k not found. I tried the following method as well:
for i in dict_to_be_deleted:
for k,v in i.items():
if "a" in k:
del i[k]
I get
Attribute Error: str object has no attribute items
But isn't it suppose to be a dictionary since dict_to_be_deleted
is a nested dictionary? I am pretty confused with this. I greatly appreciate any pointers in this regard.
To remove an element from a nested dictionary, use the del() method.
Python dictionary clear() method is used to remove all elements from the dictionary. When you have a dictionary with too many elements, deleting all elements of the dictionary one after another is a very time taken process, so use clear() method to delete all elements at once rather than deleting elements one by one.
An easy way is to use dict.pop()
instead:
data = {
'key1':
{
'a': 'key1',
'b': 'val1',
'c': 'val2'
},
'key2':
{
'a': 'key2',
'b': 'val3',
'c': 'val4'
},
'key3':
{
'a': 'key3',
'b': 'val5',
'c': 'val6'
}
}
for key in data:
data[key].pop('a', None)
print(data)
Which Outputs:
{'key1': {'b': 'val1', 'c': 'val2'}, 'key2': {'b': 'val3', 'c': 'val4'}, 'key3': {'b': 'val5', 'c': 'val6'}}
The way dict.pop()
works is that first checks if the key is in the dictionary, in this case "a"
, and it removes it and returns its value. Otherwise, return a default value, in this case None
, which protects against a KeyError
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With