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

>>> months
              {3: 'March', 12: 'December', 1: 'January'}
        The Python keyword operator del can also be used to delete a dictionary entirely.

         >>> del months #delete months
        As expected, since the dictionary months has been deleted, accessing it leads to an error:

         >>> months
              Traceback (most recent call last):
                File "<pyshell#17>", line 1, in <module>
                  months
              NameError: name 'months' is not defined. Did you mean: 'months'?
        ●  myDict.clear():  The method clear() removes all key-value pairs from the dictionary. . However, the
           dictionary object itself is not deleted.
         Example:
         >>> months = {3:'March', 11:'November', 12: 'December', 1:'January'}
         >>> months.clear()
         >>> months
              {}
        ●  myDict.get(myKey, val): The method get() returns the value of the item with the specified key (myKey),
           just like myDict[myKey], If there is a key-value pair with the  specified key (myKey), Python ignores the second
           argument (if provided). However, if there is no key-value pair with the  specified key (myKey), Python returns the
           second argument, if  provided, and None otherwise.
         Example:
         >>> myDict = { 'b':'beta', 'g':'gamma', 'a':'alpha' }
         >>> myDict.get('g')
              'gamma'
         >>> myDict['g']
              'gamma'
         >>> print(myDict.get('d'))
              None
         >>> myDict.get('d', -1)
              -1
        ●  myDict.copy(): copy() method returns the copy of the dictionary.
         Example:
         >>> myDict = { 'b':'beta', 'g':'gamma', 'a':'alpha' }
         >>> myDictCopy = myDict.copy()
         >>> myDictCopy
              {'b': 'beta', 'g': 'gamma', 'a': 'alpha'}
         >>> id(myDict), id(myDictCopy)
              (2386829086208, 2386829094976)
        Note that the variables myDict and myDictCopy refer to two different objects having the ids 2386829086208
        and 2386829094976, respectively.
        ●  myDict.fromkeys(<keys>, <value>): The method fromkeys() returns a dictionary with the specified

           keys and the specified value. Interestingly, the method does not update the existing dictionary myDict.
         Example:

         >>> subjects = {}
         >>> subjectTitle = {'Physics', 'Mathematics', 'Computer Sc.'}
         >>> marks = 0
         >>> subjects.fromkeys(subjectTitle, marks)
              {'Computer Sc.': 0, 'Mathematics': 0, 'Physics': 0}
         >>> subjects
              {}


         374   Touchpad Computer Science-XI
   371   372   373   374   375   376   377   378   379   380   381