我有这本词典:
a={'sting1':1,'string2':2,'string3':3,'string4 null':4}
Run Code Online (Sandbox Code Playgroud)
我想删除键包含空字的项目。
output={'sting1':1,'string2':2,'string3':3}
Run Code Online (Sandbox Code Playgroud)
我找到了startswith应用程序,并尝试使用 key.find('null')!=-1 ,但没有成功
做dictionary comprehension:
print({k:v for k,v in a.items() if not 'null' in k})
Run Code Online (Sandbox Code Playgroud)
如果版本低于 2.6:
print(dict((k,v) for k,v in a.iteritems() if not 'null' in k))
Run Code Online (Sandbox Code Playgroud)
看iteritems,不是items,这仅在 python 2 中(所有 python 2 版本)
“你也可以写 if 'null' not in k 有些人觉得更容易阅读”,感谢@john。