Page 103 - tp_Modula_v2.0
P. 103

09                              DICTIONARY IN



                                                                                                     PYTHON















                         Your Aim

                         to learn about:
                                  Creating a Dictionary                         Accessing a Dictionary
                                   Python Methods                                Python Functions
                                    Updating a Dictionary                        Removing or Deleting Elements of a Dictionary
                                     Some More Programs



                 A dictionary in Python is another data type which contains a collection of values in the form of key
                 value pairs. Instead of using indexing, it uses keys to access the elements. It is a heterogeneous

                 collection of data elements, where key must be unique and immutable. All the elements of a
                 dictionary are enclosed within a pair of curly brackets {}.
                 In the previous chapters, you have learned Python lists and tuples. In this chapter you will learn
                 about Python dictionary, how to create a dictionary and operations performed on it.

                     CREATING A DICTIONARY

                 To create a dictionary in Python use the following syntax:
                 d = {key1: value1, key2 : value2, ... }

                 Example:

                 d2 = {’width’: 8.5, ’height’: 11}
                 d3 = {1: ’RED’, 2: ’GREEN’, 3: ’BLUE’, }

                 Program 1: To create a dictionary.
                     Program1.py
                  File  Edit  Format  Run   Options   Window    Help
                  dict1={'Name': 'A', 'Rollno': 1}
                  print(dict1)
                  dict2={'Name': 'B', 'Rollno': 2, 'Marks': [15, 47, 54] }
                  print(dict2)
                  dict3=dict({'Name': 'C', 'Rollno': 3})
                  print(dict3)
                  dict4=dict([('Name', 'D'), ('Rollno', 4)])
                  print(dict4)




                                                                                           Dictionary in Python   101
   98   99   100   101   102   103   104   105   106   107   108