Page 374 - Computer Science Class 11 With Functions
P. 374

14.5 Dictionary Methods

        Python provides several methods for manipulating dictionaries. Unlike strings and tuples, a dictionary is a mutable
        object. To invoke a method associated with a dictionary object, the dict object is followed by a dot, followed by the
        name of the method, followed by a pair of parentheses that encloses the arguments (if any) required for invoking the
        method. Using  a dictionary object  myDict, we describe some methods that apply to the dictionaries

        ●  myDict.keys(): The method keys() returns a dict_keys object comprising all the keys included in the
           dictionary. We can iterate over the keys in the dict_keys  object and also check for membership of a key.
           However, dict_keys does not support indexing.

         Example:
         >>> subjects
              {'Sanskrit': 78, 'English': 185, 'Maths': 88, 'Hindi': 90}
         >>> subjects.keys()
              dict_keys(['Sanskrit', 'English', 'Maths', 'Hindi'])
         >>> 'English' in subjects.keys()
              True
         >>> for subject in subjects.keys():
         ...     print(subject, end = ' ')
         ...
         ...
              Sanskrit English Maths Hindi
         >>> subjects.keys()[0]
              Traceback (most recent call last):
                File "<pyshell#38>", line 1, in <module>
                  subjects.keys()[0]
              TypeError: 'dict_keys' object is not subscriptable


                 Consider the dictionary, myDict.
                 >>> myDict = { 'b':'beta', 'g':'gamma', 'a':'alpha' }
                 Display all the keys of myDict.


        ●  myDict.values(): The method  values() returns  a  dict_values  object  comprising  all  the  values
           included  in  the  dictionary.  We  can  iterate  over  the  values  in  the  dict_values  object  and  also,  check  for
           membership of a value in a dict_values. However, dict_values does not support indexing.
         Example
         >>> 78 in subjects.values()
              True
         >>> for subjectCode in subjects.values():
         ...     print(subjectCode, end=' ')
         ...
         ...
              78 185 88 90
        ●  myDict.items(): The method  items() returns a  dict_items object comprising  the set of items
           included in the dictionary. We can check for membership of an item  in a dict_items and iterate over the items
           in the dict_items object. However, dict_items does not support indexing.

         Example:
         >>> subjects = {'Sanskrit': 78, 'English': 185, 'Maths': 88, 'Hindi': 90}
         >>> ('English', 185) in subjects.items()
              True
              for subject in subjects.items():
         ...     print(subject, end=' ')

         372   Touchpad Computer Science-XI
   369   370   371   372   373   374   375   376   377   378   379