Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary: Remove all the keys that begins with s

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?

like image 791
user469652 Avatar asked Jan 11 '11 02:01

user469652


People also ask

Can you remove keys from dictionary Python?

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.

How do I remove a key from a dictionary list?

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.


3 Answers

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]
like image 157
nosklo Avatar answered Oct 03 '22 07:10

nosklo


This should do it:

for k in dic.keys():
  if k.startswith('s_'):
    dic.pop(k)
like image 22
Spaceghost Avatar answered Oct 03 '22 06:10

Spaceghost


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)
like image 11
Sérgio Avatar answered Oct 03 '22 07:10

Sérgio