Page 210 - Information_Practice_Fliipbook_Class11
P. 210
In the above example, the first statement creates an empty dictionary, and the subsequent assignment statements add
key-value pairs to the dictionary. The Greek letter corresponding to the key 'b' may be retrieved as follows:
>>> myDict['b']
'beta'
The expression dict() also creates an empty dictionary, as shown below:
>>> dictionary = dict() # Create an empty dictionary
The function len(myDict)yields the number of key-value pairs in a dictionary. For example,
>>> len(myDict)
3
8.2 Aggregate Operations min, max, and sum
Given a dict object, you can use min(), max(), and sum() functions on its set of keys. For example, consider the
dict object months that maps month numbers to their names:
>>> months = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June',
7:'July',8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}
>>> min(months)
1
>>> max(months)
12
Note that the expression min(months) yields the least value of the key in the dictionary months. Similarly, the
expression max(months)yields the maximum value of the key in the dictionary months.
The sum() function can be used to add up the values in a dictionary. However, using the sum() function directly on a
dictionary will only add up the keys of the dictionary, not the values.
For example,
myDict = {1: 10, 2: 20, 3: 30}
sumKeys = sum(myDict)
print(sumKeys) # Output: 6
In this example, the sum() function is called on the dictionary myDict. However, instead of adding up the values of the
dictionary, it adds up the keys of the dictionary (1, 2, 3). This results in an output of 6.
To add up the values of a dictionary using the sum() function, you can use the values() method to get a list of the
dictionary's values and then pass that list to the sum() function.
For example,
myDict = {1: 10, 2: 20, 3: 30}
sumValues = sum(myDict.values())
print(sumValues) # Output: 60
In this example, the values() method is called on the dictionary myDict to get a list of its values. This list ([10,
20, 30]) is then passed to the sum() function, which adds up the values and returns the sum of values (60).
8.3 Nested Dictionary
Python also supports a nested dictionary. A nested dictionary is a dictionary that contains one or more dictionaries as
values. Each of the inner dictionaries can contain its own set of keys and values.
Here is an example of a nested dictionary:
myDict = {
196 Touchpad Informatics Practices-XI

