SoFunction
Updated on 2024-11-10

Methods to perform deletion of Python dictionary elements

1. Python dictionary's clear() method (removes all elements from the dictionary)

#!/usr/bin/python
# -*- coding: UTF-8 -*-
dict = {'name': 'My blog address', 'alexa': 10000, 'url': '/uuihoo/'}
(); # Clear all dictionary entries

2. The pop() method of a Python dictionary (removes the value corresponding to a given key of the dictionary; the return value is the value that was removed)

#!/usr/bin/python
# -*- coding: UTF-8 -*-
site= {'name': 'My blog address', 'alexa': 10000, 'url':'/uuihoo/'}
pop_obj=('name') # Delete the key-value pair to be deleted, e.g., the key-value pair {'name':'my blog address'}
print pop_obj # exports :My blog address

3. The popitem() method for Python dictionaries (returns and removes a random pair of keys and values from a dictionary)

#!/usr/bin/python
# -*- coding: UTF-8 -*-
site= {'name': 'My blog address', 'alexa': 10000, 'url':'/uuihoo/'}
pop_obj=() # Randomly return and delete a key-value pair
print pop_obj # The output may be{'url','/uuihoo/'}

4. del global method (can delete a single element can also empty the dictionary, empty only one operation)

#!/usr/bin/python
# -*- coding: UTF-8 -*-
site= {'name': 'My blog address', 'alexa': 10000, 'url':'/uuihoo/'}
del site['name'] # Delete entry with key 'name'
del site # Clear all dictionary entries

Above is the method of Python dictionary elements to delete the details, more information about Python delete dictionary elements please pay attention to my other related articles!