Original website: http://www.iplaypython.com/jinjie/jj116.html
Like other python built-in data types, dictionary dict also has some practical ways to do it. Here we are talking about the dictionary deletion method : Clear (), pop (), and Popitem (), the three methods have different functions, the operation method and the return value are not the same. Next, look at what the specific usage of these dictionary-specific methods is.
Dictionary Clear () method
The clear () method is used to clear all the data in the dictionary because it is in-place operation, so none is returned (it can also be understood as no return value)
>>> x[' name '] = ' Lili '
>>> x[' age '] = 20
>>> x
{' Age ': ' ' name ': ' Lili '}
>>> Returned_value = X.clear ()
>>> x
{ }
>>> Print Returned_value
None
What are the characteristics of the clear () method of the dictionary:
>>> f = {' key ': ' Value '}
>>> a = f
>>> A
{' key ': ' Value '}
>>> F.clear ()
>>> F
{}
>>> A
{}
When the original dictionary is referenced, the elements in the original dictionary are emptied, and the elements in the A dictionary are cleared at the same time using the clear () method.
Dictionary pop () method
Remove Dictionary data The Pop () method does this by deleting the value corresponding to the given key, returning the value and removing it from the dictionary. Note that the dictionary pop () method works completely differently than the list pop () method.
>>> x = {' A ': 1, ' B ': 2}
>>> X.pop (' a ')
1
>>> x
{' B ': 2}
Dictionary Popitem () method
The dictionary Popitem () method acts by randomly returning and deleting a pair of keys and values (items) in the dictionary. Why is it randomly deleted? Because dictionaries are unordered, there is no so-called "last" or other order. It is very efficient to use the Popitem () method when working with the task of deleting items individually.
>>> x
{' URL ': ' www.iplaypython.com ', ' title ': ' Python Web site '}
>>> X.popitem ()
(' url ', ' www.iplaypython.com ')
>>> x
{' title ': ' Python Web site '}
Python Dictionary Delete element clear, pop, Popitem