Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting Items based on Keys in nested Dictionaries in python

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.

like image 614
Ravi Kumar Avatar asked Dec 29 '17 04:12

Ravi Kumar


People also ask

How do I remove something from a nested dictionary Python?

To remove an element from a nested dictionary, use the del() method.

Can I use Clear () method to delete the dictionary?

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.


1 Answers

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.

like image 139
RoadRunner Avatar answered Oct 18 '22 17:10

RoadRunner