我有这本字典:
a={'sting1':1,'string2':2,'string3':3,'string4 null':4}
我想删除键中包含单词 null 的项。
output={'sting1':1,'string2':2,'string3':3}
我找到了 startswith 应用程序,并尝试使用 key.find('null')!=-1 ,但没有成功
请您参考如下方法:
执行字典理解:
print({k:v for k,v in a.items() if not 'null' in k})
如果版本低于 2.6:
print(dict((k,v) for k,v in a.iteritems() if not 'null' in k))
请参阅 iteritems,而不是 items,它仅在 python 2 中(所有 python 2 版本)
“你也可以写 if 'null' not in k,有些人觉得这样更容易阅读”,感谢@john。
