Python-从字典中删除键的方法
字典还用于多种日常应用中,例如日间编程,Web开发和AI/ML编程,从而使其成为一个有用的容器。因此,了解实现与词典使用相关的不同任务的方法总是有好处的。
示例
# using del
# Initializing dictionary
test_dict = {"Vishesh" : 29, "Ram" : 21, "Vishal" : 27, "Prashant" : 25}
# Printing dictionary before removal
print ("The dictionary before performing remove is : " + str(test_dict))
# Using del to remove a dict
del test_dict['Vishal']
# Printing dictionary after removal
print ("The dictionary after remove is : " + str(test_dict))
# using pop()# Initializing dictionary
test_dict = {"Vishesh" : 29, "Ram" : 21, "Vishal" : 27, "Prashant" : 25}
# Printing dictionary before removal
print ("The dictionary before performing remove is : " + str(test_dict))
# Using pop() to remove a dict. pair
removed_value = test_dict.pop('Ram')
# Printing dictionary after removal
print ("The dictionary after remove is : " + str(test_dict))
print ("The removed key's value is : " + str(removed_value))
# Using pop() to remove a dict. pair doesn't raise exception
# assigns 'No Key found' to removed_value
removed_value = test_dict.pop('Nilesh', 'No Key found')
# Printing dictionary after removal
print ("The dictionary after remove is : " + str(test_dict))
print ("The removed key's value is : " + str(removed_value))
# using items() + dict comprehension
# Initializing dictionary
test_dict = {"Vishesh" : 29, "Ram" : 21, "Vishal" : 27, "Prashant" : 25}
# Printing dictionary before removal
print ("The dictionary before performing remove is : " + str(test_dict))
# Using items() + dict comprehension to remove a dict. pair
new_dict = {key:val for key, val in test_dict.items() if key != 'Prashant}
# Printing dictionary after removal
print ("The dictionary after remove is : " + str(new_dict))
'热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短