I've got a dictionary like
dic = {'s_good': 23, 's_bad': 39, 'good_s': 34}
I want to remove all the keys that begins with 's_'
So in this case first two will be removed.
Is there any efficient way to do so?
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.
Method #1 : Using loop + del The combination of above functions can be used to solve this problem. In this, we iterate for all the keys and delete the required key from each dictionary using del.
for k in dic.keys():
if k.startswith('s_'):
del dic[k]
* EDIT *
now in python 3 , years after the original answer, keys()
returns a view into the dict so you can't change the dict size.
One of the most elegant solutions is a copy of the keys:
for k in list(dic.keys()):
if k.startswith('s_'):
del dic[k]
This should do it:
for k in dic.keys():
if k.startswith('s_'):
dic.pop(k)
With python 3 to avoid the error:
RuntimeError: dictionary changed size during iteration
This should do it:
list_keys = list(dic.keys())
for k in list_keys:
if k.startswith('s_'):
dic.pop(k)
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