我们可以通过以下方式从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'}
如果我们在外壳中运行它, 其效果类似于
{'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
如果您发现它有用, 请分叉此实体以供将来参考。