静默地从 Python dict 中删除键

我有一个巨蟒字典,我想悄悄地删除任何 None''键从我的字典,所以我想出了这样的东西:

try:
del my_dict[None]
except KeyError:
pass


try:
del my_dict['']
except KeyError:
pass

正如您所看到的,它的可读性较差,并且导致我编写重复的代码。因此,我想知道 Python 中是否有一种方法可以在不抛出键错误的情况下从 dict 中删除任何键?

42726 次浏览

The following will delete the keys, if they are present, and it won't throw an error:

for d in [None, '']:
if d in my_dict:
del my_dict[d]

You could use the dict.pop method and ignore the result:

for key in [None, '']:
d.pop(key, None)

You can do this:

d.pop("", None)
d.pop(None, None)

Pops dictionary with a default value that you ignore.

You can try:

d = dict((k, v) for k,v in d.items() if k is not None and k != '')

or to remove all empty-like keys

d = dict((k, v) for k,v in d.items() if k )