Page 371 - Computer Science Class 11 With Functions
P. 371
The above statement creates an object subject of type dict. Each element of the dictionary subjects is a
subject:subject code pair. (See Fig 14.1).
Fig 14.1: Name subjects referring to an object of type dict
To get the value that goes with a key, you put the key in square brackets after the dict object. For example, the
subject code for the subject (key) 'English' may be found by following the dict object subjects by the key
'English' enclosed in square brackets.
>>> subjects['English']
85
Suppose, the subject code for the key 'English' changes to 185. To reflect this change in the dict object subjects,
we can modify the value in the English:85 pair using an assignment statement, as illustrated below:
>>> subjects['English'] = 185
>>> subjects['English']
185
>>> subjects
{'Sanskrit': 78, 'English': 185, 'Maths': 88, 'Hindi': 90}
As expected, an attempt to access a value associated with a non-existent key yields a KeyError. For example, if you
try to get the value of the non-existent key 'History', you get an error like the one below:
>>> subjects = {'Sanskrit': 78, 'English': 185, 'Maths': 88, 'Hindi': 90}
>>> subject = 'History'
>>> subjects[subject]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
subjects[subject]
KeyError: 'History'
To avoid KeyError, when in doubt, one should check for the existence of a key in the dict object prior to accessing
its value using the membership operator in. For example,
>>> subject= 'History'
>>> if subject in subjects:
... print(subjects['subject'])
... else:
... print(subject, 'is not in the dictionary subjects')
...
...
History is not in the dictionary subjects
In the above example, the membership condition subject in subjects yields False because the dict object
subjects does not include any key:value pair having 'History' as the key check the membership of a key in a
dictionary. It returns True when the key is present, False otherwise.
Next, let us examine some more examples of operations on dictionaries. We've already seen that the assignment
statement can be used to change the value associated with a key. An assignment statement is also used to add a new
key-value pair to a dict object, as illustrated below:
Dictionaries 369

