Page 208 - Information_Practice_Fliipbook_Class11
P. 208

8                                       PYTHON DICTIONARIES














          Chapter Outline


          8.1 Dictionary in Python                           8.2 Aggregate Operations (min, max, and sum)
          8.3 Nested Dictionary                              8.4 Dictionary Methods
          8.5 Traversing a Dictionary                        8.6 Sorting Keys/ Values of a Dictionary

          8.7 Building a Thesaurus




        Introduction

        We are already familiar with the objects of the type list. Lists map integer indexes to objects of arbitrary types.
        Python dictionaries take the generalisation a step further by mapping the objects of arbitrary immutable types to
        objects of arbitrary types, including mutable types. Thus, a dictionary may be thought of as a collection of key-value
        pairs, i.e., a set of keys of immutable types that map to a set of values. For example, a dictionary of synonyms might
        comprise (word, synonyms)pairs, where a word is an str object, and synonyms is a list object comprising
        the synonyms of the word. In this chapter, we will learn about dictionaries and their applications.


        8.1 Dictionary in Python

        A dictionary is an unordered set of key: value pairs. A dictionary (an object of type dict) is defined in Python by
        enclosing the comma-separated key: value pairs in braces. An empty pair of braces denote an empty dictionary. The
        keys in a dictionary are required to be unique. However, the same value may be associated with multiple keys. As
        keys are used to search for a key-value pair, given a key-value pair, Python disallows modification of keys. So, objects
        of immutable types, strings, numbers, and tuples are used as keys. However, the values associated with keys may be
        objects of any type. The syntax for defining and naming a dictionary is as follows:

        {key1:value1, key2:value2, ...}
        For example,

         >>> subjects = {'Sanskrit':78, 'English':85, 'Maths':88, 'Hindi':90}
         >>> subjects
              {'Sanskrit': 78, 'English': 85, 'Maths': 88, 'Hindi': 90}
        The above statement creates an object subjects of type dict. Each element of the dictionary subjects is a
        subject:subjectCode pair. (See Fig 8.1).




          194  Touchpad Informatics Practices-XI
   203   204   205   206   207   208   209   210   211   212   213