Easy Tutorial
❮ Python Mongodb Python String Translate ❯

Python Remove Dictionary Key-Value Pairs

Python3 Examples

Given a dictionary, remove dictionary key-value pairs.

Example 1: Using del to Remove

test_dict = {"tutorialpro": 1, "Google": 2, "Taobao": 3, "Zhihu": 4}

# Print the original dictionary
print("Dictionary before removal: " + str(test_dict))

# Use del to remove 'Zhihu'
del test_dict['Zhihu']

# Print the dictionary after removal
print("Dictionary after removal: " + str(test_dict))

# Removing a non-existent key will raise an error
# del test_dict['Baidu']

Executing the above code outputs:

Dictionary before removal: {'tutorialpro': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
Dictionary after removal: {'tutorialpro': 1, 'Google': 2, 'Taobao': 3}

Example 2: Using pop() to Remove

test_dict = {"tutorialpro": 1, "Google": 2, "Taobao": 3, "Zhihu": 4}

# Print the original dictionary
print("Dictionary before removal: " + str(test_dict))

# Use pop to remove 'Zhihu'
removed_value = test_dict.pop('Zhihu')

# Print the dictionary after removal
print("Dictionary after 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 raise an exception, we can customize the message
removed_value = test_dict.pop('Baidu', 'No such key')

# Print the dictionary after removal
print("Dictionary after removal: " + str(test_dict))
print("The removed value is: " + str(removed_value))

Executing the above code outputs:

Dictionary before removal: {'tutorialpro': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
Dictionary after removal: {'tutorialpro': 1, 'Google': 2, 'Taobao': 3}
The value corresponding to the removed key is: 4

Dictionary after removal: {'tutorialpro': 1, 'Google': 2, 'Taobao': 3}
The removed value is: No such key

Example 3: Using items() to Remove

test_dict = {"tutorialpro": 1, "Google": 2, "Taobao": 3, "Zhihu": 4}

# Print the original dictionary
print("Dictionary before removal: " + str(test_dict))

# Use items() to remove 'Zhihu'
new_dict = {key: val for key, val in test_dict.items() if key != 'Zhihu'}

# Print the dictionary after removal
print("Dictionary after removal: " + str(new_dict))

Executing the above code outputs:

Dictionary before removal: {'tutorialpro': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
Dictionary after removal: {'tutorialpro': 1, 'Google': 2, 'Taobao': 3}

Python3 Examples

❮ Python Mongodb Python String Translate ❯