Python - 从字典中删除键的方法
pythonserver side programmingprogramming更新于 2025/9/17 10:52:17
字典用于多种实际应用,例如日常编程、Web 开发和 AI/ML 编程,因此它是一个非常有用的容器。因此,了解实现与字典使用相关的不同任务的方法总是有益的。
示例
# 使用 del
# 初始化字典
test_dict = {"Vishesh" : 29, "Ram" : 21, "Vishal" : 27, "Prashant" : 25}
# 打印移除前的字典
print ("执行移除前的字典是 : " + str(test_dict))
# 使用 del 移除字典
del test_dict['Vishal']
# 打印移除后的字典
print ("移除后的字典是 : " + str(test_dict))
# 使用 pop()
# 初始化字典
test_dict = {"Vishesh" : 29, "Ram" : 21, "Vishal" : 27, "Prashant" : 25}
# 打印移除前的字典
print ("执行移除前的字典是 : " + str(test_dict))
# 使用 pop() 移除字典。 pair
removed_value = test_dict.pop('Ram')
# 打印移除后的字典
print ("移除后的字典为:" + str(test_dict))
print ("移除的键的值为:" + str(removed_value))
# 使用 pop() 移除字典。pair 不会引发异常
# 将 'No Key found' 赋值给 removed_value
removed_value = test_dict.pop('Nilesh', 'No Key found')
# 打印删除后的字典
print ("删除后的字典是:" + str(test_dict))
print ("删除的键的值是:" + str(removed_value))
# 使用 items() + 字典推导式
# 初始化字典
test_dict = {"Vishesh" : 29, "Ram" : 21, "Vishal" : 27, "Prashant" : 25}
# 打印删除前的字典
print ("执行删除前的字典是:" + str(test_dict))
# 使用 items() + 字典推导式删除字典。对
new_dict = {key:val for key, val in test_dict.items() if key != 'Prashant}
# 打印删除后的字典
print ("删除后的字典是:" + str(new_dict))
'
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

