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

14                                                             DICTIONARIES














          Chapter Outline


          14.1 Dictionary in Python
          14.2 Aggregate operations min, max, and sum that can be applied on dictionaries
          14.3 Nested Dictionary                             14.4 Traversing a Dictionary
          14.5 Dictionary Methods                            14.6 Sorting Keys/ Values of a Dictionary
          14.7 Building a Thesaurus





        Introduction
        We are already familiar with objects of type tuple, list, and str (strings). An str object defines a mapping of
        integer indexes to characters. For example, the str object 'beautiful' maps integers 0, 1, 2, …, 8 to characters
        'b', 'e', 'a', 'u', 't', 'i', 'f', 'u', and 'l'. Similarly, lists and tuples map integer indexes
        to objects of arbitrary types. The Python dictionaries take the generalisation a step further, by mapping 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.

        14.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 denotes 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
        the 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}


         368   Touchpad Computer Science-XI
   365   366   367   368   369   370   371   372   373   374   375