I have a python dict and I'd like to silently remove either None
and ''
keys from my dictionary so I came up with something like this:
try: del my_dict[None] except KeyError: pass try: del my_dict[''] except KeyError: pass
As you see, it is less readable and it causes me to write duplicate code. So I want to know if there is a method in python to remove any key from a dict without throwing a key error?
You can remove duplicates from a Python using the dict. fromkeys(), which generates a dictionary that removes any duplicate values. You can also convert a list to a set.
To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.
You can do this:
d.pop("", None) d.pop(None, None)
Pops dictionary with a default value that you ignore.
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