Page 427 - Computer Science V2.0 Class 11
P. 427
● myDict.setdefault(key, [value]): setdefault() method returns the value of the item with the
specified key. However, if the key does not exist, then the key is inserted in the dictionary and the key is associated
with the value passed as the second parameter.
Example:
>>> myDict = { 'b':'beta', 'g':'gamma', 'a':'alpha' }
>>> myDict.setdefault('a')
'alpha'
>>> myDict.setdefault('a', 'aa')
'alpha'
>>> myDict
{'b': 'beta', 'g': 'gamma', 'a': 'alpha'}
>>> myDict.setdefault('d','delta')
'delta'
>>> myDict
{'b': 'beta', 'g': 'gamma', 'a': 'alpha', 'd': 'delta'}
14.6 Sorting Keys/ Values of a Dictionary
sorted(): The method sorted() is used to sort the dictionary by the keys or by the values. By default, the
method sorted() returns a list of keys in the dictionary in ascending order of the keys.
Example:
>>> myDict = { 'b':'beta', 'g':'gamma', 'a':'alpha' }
>>> sorted(myDict) # sorted(myDict.keys())
['a', 'b', 'g']
>>> sorted(myDict, reverse = True)
['g', 'b', 'a']
>>> sorted(myDict.values())
['alpha', 'beta', 'gamma']
Example: Use sorted() method to print all key-value pairs with respect to keys.
>>> for key in sorted(myDict.keys()):
... print(key, ':', myDict[key])
a : alpha
b : beta
g : gamma
The built-in functions and methods for dictionary are summarized in the following table:
Table 14.1: Built-in functions and methods for dictionary
Method Description Example
min(dictionary) Yields the least value of the key in the >>>dictionary =
dictionary. {1:'A',2:'B',3:'C'}
>>>min(dictionary)
1
max(dictionary) Yields the maximum value of the key in >>>dictionary =
the dictionary. {1:'A',2:'B',3:'C'}
>>>max(dictionary)
3
len(dictionary) Yields the number of key-value pairs in a >>>dictionary =
dictionary. {1:'A',2:'B',3:'C'}
>>>len(dictionary)
3
Dictionaries 413

