我有一本像
这样的词典dic = {'s_good': 23, 's_bad': 39, 'good_s': 34}
我想删除所有以's _'
开头的键所以在这种情况下,前两个将被删除。
有没有有效的方法呢?
答案 0 :(得分:22)
这应该这样做:
for k in dic.keys():
if k.startswith('s_'):
dic.pop(k)
答案 1 :(得分:18)
for k in dic.keys():
if k.startswith('s_'):
del dic[k]
答案 2 :(得分:7)
使用python 3来避免错误:
RuntimeError: dictionary changed size during iteration
这应该这样做:
list_keys = list(dic.keys())
for k in list_keys:
if k.startswith('s_'):
dic.pop(k)
答案 3 :(得分:5)
这样的事情怎么样:
dic = dict( [(x,y) for x,y in dic.items() if not x.startswith('s_')] )
答案 4 :(得分:3)
您可以在Python 3中使用字典理解:
{k: v for k, v in dic.items() if not k.startswith("s_")}
Python 2中的这种类似语法也做了同样的事情:
dict((k, v) for k, v in dic.items() if not k.startswith("s_"))
请注意,这两个字词都会创建一个新字典(如果您愿意,可以将其分配回dic
),而不是改变现有字典。