Page 209 - Information_Practice_Fliipbook_Class11
P. 209

Fig 8.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 do not include any key: value pair having 'History'.

            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:

             >>> myDict = {}  # Create an empty dictionary
             >>> myDict['a'] = 'alpha'
             >>> myDict['b'] = 'beta'
             >>> myDict['g'] = 'gamma'
             >>> myDict
                 {'a': 'alpha', 'b': 'beta', 'g': 'gamma'}


                                                                                             Python Dictionaries  195
   204   205   206   207   208   209   210   211   212   213   214