我有一个类似于字典的东西
dic = {'s_good': 23, 's_bad': 39, 'good_s': 34}
我想删除所有以's_'开头的键
在这种情况下,前两个将被删除。
是否有更有效的方法来做到这一点?
我有一个类似于字典的东西
dic = {'s_good': 23, 's_bad': 39, 'good_s': 34}
我想删除所有以's_'开头的键
在这种情况下,前两个将被删除。
是否有更有效的方法来做到这一点?
for k in dic.keys():
if k.startswith('s_'):
del dic[k]
* 编辑 *
现在在 Python 3 中,距离最初的回答已经过去了很多年,keys()
返回一个字典的视图,因此您不能更改字典的大小。
最优雅的解决方案之一是对键进行复制:
for k in list(dic.keys()):
if k.startswith('s_'):
del dic[k]
for k in dic.keys():
if k.startswith('s_'):
dic.pop(k)
keys
是一个dictview
而不是一个列表。 - agffor k in dic.keys():
而不是 for k in dic:
。 - tqjustc使用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)
dic = {k: v for k, v in dic.items() if not k.startswith("s_")}
dic 变量),而不是改变现有的字典。
dic = dict( [(x,y) for x,y in dic.items() if not x.startswith('s_')] )
del
表示您希望删除条目,而pop
表示您希望检索它。因此,在这种情况下,我更喜欢使用del
而不是pop
。 ;) - johndodo