我们可以通过以下一些方法从 Python 字典中删除一个键。
使用del 关键字;不过,这与您所做的几乎相同 -
myDict = {'one': 100, 'two': 200, 'three': 300 }
print(myDict) # {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : del myDict['one']
print(myDict) # {'two': 200, 'three': 300}
或者
我们可以这样做:
但请记住,在此过程中,实际上它不会删除字典中的任何键,而是从该字典中排除特定键。此外,我观察到它返回的字典与myDict 的排序不同。
myDict = {'one': 100, 'two': 200, 'three': 300, 'four': 400, 'five': 500}
{key:value for key, value in myDict.items() if key != 'one'}
如果我们在 shell 中运行它,它会执行类似{'five': 500, 'four': 400, 'three': 300, 'two': 200} 的东西——注意它与myDict 的顺序不同。同样,如果我们尝试打印myDict,那么我们可以看到所有键,包括我们通过这种方法从字典中排除的键。但是,我们可以通过将以下语句分配给变量来创建一个新字典:
var = {key:value for key, value in myDict.items() if key != 'one'}
现在如果我们尝试打印它,那么它将遵循父顺序:
print(var) # {'two': 200, 'three': 300, 'four': 400, 'five': 500}
或者
使用pop() 方法。
myDict = {'one': 100, 'two': 200, 'three': 300}
print(myDict)
if myDict.get('one') : myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
del 和pop 的区别在于,使用pop() 方法,如果需要,我们实际上可以存储键的值,如下所示:
myDict = {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : var = myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
print(var) # 100
fork this gist 以供将来参考,如果您觉得这很有用。