开发者

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 w开发者_Python百科ill be removed.

Is there any efficient way to do so?


This should do it:

for k in dic.keys():
  if k.startswith('s_'):
    dic.pop(k)


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]


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)


You can use a dictionary comprehension:

dic = {k: v for k, v in dic.items() if not k.startswith("s_")}

Note that this creates a new dictionary (which you then assign back to the dic variable) rather than mutating the existing dictionary.


How about something like this:

dic = dict( [(x,y) for x,y in dic.items() if not x.startswith('s_')] )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜