Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove key from nested dictionary

I currently have a nested dictionary like:

[{‘rule’: {‘actions’: {‘allow’: False}, ‘dl_type’: 2048, ‘ipv4_dst’: ‘192.168.50.0/24’, ‘ipv4_src’: ‘192.168.50.20’}}, {‘rule’: {‘actions’: {‘allow’: False}, ‘dl_type’: 2048, ‘ipv4_dst’: ‘192.168.50.0/24’, ‘ipv4_src’: ‘192.168.50.10’}}, {‘rule’: {‘actions’: {‘allow’: True}}}]

I want to remove this from my nested dictionary:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{‘rule’: {‘actions’: {‘allow’: False}, ‘dl_type’: 2048, ‘ipv4_dst’: ‘192.168.50.0/24’, ‘ipv4_src’: ‘192.168.50.10’}}

How would I do something like this? I don’t think I can remove the dictionary based on the key because it looks like there are multiple dictionaries that contain the same keys. It sounds like it should be simple, but I can’t seem to remove that dictionary and the nested dictionaries inside of it (maybe because I’m burned out for the day). Any help is greatly appreciated on this!

>Solution :

It looks like the difference between the bolded element and the previous element is the value for ipv4_src i.e., 192.168.50.10, therefore you could use a list comprehension to remove the dictionary with that:

org_list = [{
    'rule': {
        'actions': {
            'allow': False
        },
        'dl_type': 2048,
        'ipv4_dst': '192.168.50.0/24',
        'ipv4_src': '192.168.50.20'
    }
}, {
    'rule': {
        'actions': {
            'allow': False
        },
        'dl_type': 2048,
        'ipv4_dst': '192.168.50.0/24',
        'ipv4_src': '192.168.50.10'  # this is the difference
    }
}, {
    'rule': {
        'actions': {
            'allow': True
        }
    }
}]

new_list = [
    d for d in org_list if d['rule'].get('ipv4_src', '') != '192.168.50.10'
]

print(new_list)

Output:

[{'rule': {'actions': {'allow': False}, 'dl_type': 2048, 'ipv4_dst': '192.168.50.0/24', 'ipv4_src': '192.168.50.20'}}, {'rule': {'actions': {'allow': True}}}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading