use*_*652 12 python dictionary
我有一本字典
dic = {'s_good': 23, 's_bad': 39, 'good_s': 34}
Run Code Online (Sandbox Code Playgroud)
我想删除所有以's_'开头的键
所以在这种情况下,前两个将被删除.
有没有有效的方法呢?
Spa*_*ost 22
这应该这样做:
for k in dic.keys():
if k.startswith('s_'):
dic.pop(k)
Run Code Online (Sandbox Code Playgroud)
nos*_*klo 18
for k in dic.keys():
if k.startswith('s_'):
del dic[k]
Run Code Online (Sandbox Code Playgroud)
使用python 3避免错误:
RuntimeError: dictionary changed size during iteration
Run Code Online (Sandbox Code Playgroud)
应该这样做:
list_keys = list(dic.keys())
for k in list_keys:
if k.startswith('s_'):
dic.pop(k)
Run Code Online (Sandbox Code Playgroud)
您可以使用字典理解:
dic = {k: v for k, v in dic.items() if not k.startswith("s_")}
Run Code Online (Sandbox Code Playgroud)
请注意,这会创建一个新字典(然后您将其分配回dic
变量)而不是改变现有字典。
这样的事情怎么样:
dic = dict( [(x,y) for x,y in dic.items() if not x.startswith('s_')] )
Run Code Online (Sandbox Code Playgroud)