Page 213 - Information_Practice_Fliipbook_Class11
P. 213
● myDict.popitem(): The method popitem() removes the last item (key-value pair) from the dictionary. In
Python versions prior to 3.7, this method removes a random item.
Example:
>>> months = {3:'March', 11:'November', 12: 'December', 1:'January'}
>>> months.popitem()
(1, 'January')
>>> months
{3: 'March', 11: 'November', 12: 'December'}
● del Operator: The Python operator del can also be used to remove key-value pair(s) from a dictionary.
Example:
>>> months = {3:'March', 11:'November', 12: 'December', 1:'January'}
>>> del months[11]
>>> months
{3: 'March', 12: 'December', 1: 'January'}
The Python operator del can also be used to delete a dictionary entirely.
>>> del months #delete months
As expected, since the dictionary months has been deleted, accessing it leads to an error:
>>> months
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
months
NameError: name 'months' is not defined. Did you mean: 'months'?
● myDict.clear(): The method clear() removes all key-value pairs from the dictionary. However, the
dictionary object itself is not deleted.
Example:
>>> months = {3:'March', 11:'November', 12: 'December', 1:'January'}
>>> months.clear()
>>> months
{}
● myDict.get(myKey, val): The method get() returns the value of the item with the specified key (myKey),
just like myDict[myKey]. If there is a key-value pair with the specified key (myKey), Python ignores the second
argument (if provided). However, if there is no key-value pair with the specified key (myKey), Python returns the
second argument, if provided, and None otherwise.
Example:
>>> myDict = { 'b':'beta', 'g':'gamma', 'a':'alpha' }
>>> myDict.get('g')
'gamma'
>>> myDict['g']
'gamma'
>>> print(myDict.get('d'))
None
>>> myDict.get('d', -1)
-1
● myDict.copy(): copy() method returns the copy of the dictionary.
Example:
>>> myDict = { 'b':'beta', 'g':'gamma', 'a':'alpha' }
>>> myDictCopy = myDict.copy()
>>> myDictCopy
{'b': 'beta', 'g': 'gamma', 'a': 'alpha'}
>>> id(myDict), id(myDictCopy)
(2386829086208, 2386829094976)
Python Dictionaries 199

