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:
{'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!
CodePudding user response:
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}}}]