Python Remove Dictionary Key/Value Pairs

Document 对象参考手册Python3 Examples

Given a dictionary, remove the key/value pairs from the dictionary.

Example 1: Using del to remove

test_dict = {"Example" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4} # Output the original dictionary print ("Before dictionary removal:" + str(test_dict)) # Use del to remove Zhihu del test_dict['Zhihu'] # Output the dictionary after removal print ("After dictionary removal:" + str(test_dict)) # Removing a non-existent key will cause an error #del test_dict['Baidu']

Executing the above code produces the following output:

字典移除前 : {'Example': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
字典移除后 : {'Example': 1, 'Google': 2, 'Taobao': 3}

Example 2: Using pop() to remove

test_dict = {"Example" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4} # Output the original dictionary print ("Before dictionary removal:" + str(test_dict)) # Use pop to remove Zhihu removed_value = test_dict.pop('Zhihu') # Output the dictionary after removal print ("After dictionary removal:" + str(test_dict)) print ("The value corresponding to the removed key is:" + str(removed_value)) print ('\r') # Using pop() to remove a non-existent key will not cause an exception; we can customize the prompt message removed_value = test_dict.pop('Baidu', 'No such key') # Output the dictionary after removal print ("After dictionary removal:" + str(test_dict)) print ("The removed value is:" + str(removed_value))

Executing the above code produces the following output:

字典移除前 : {'Example': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
字典移除后 : {'Example': 1, 'Google': 2, 'Taobao': 3}
移除的 key 对应的 value 为 : 4

字典移除后 : {'Example': 1, 'Google': 2, 'Taobao': 3}
移除的值为 : 没有该键(key)

Example 3: Using items() to remove

test_dict = {"Example" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4} # Output the original dictionary print ("Before dictionary removal:" + str(test_dict)) # Use pop to remove Zhihu new_dict = {key:val for key, val in test_dict.items() if key != 'Zhihu'} # Output the dictionary after removal print ("After dictionary removal:" + str(new_dict))

Executing the above code produces the following output:

字典移除前 : {'Example': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
字典移除后 : {'Example': 1, 'Google': 2, 'Taobao': 3}

Document 对象参考手册Python3 Examples

Other Extensions