Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 139 - 2615_KEC
P. 139

    CREATING A DICTIONARY
                     To create a dictionary, you need to place key–value pairs inside curly brackets { }. Each key and
                     value is separated by a colon (:), and each pair is separated by a comma. The syntax for creating
                     a dictionary is as follows:
                     dictionary_name = {key1: value1, key2: value2, key3: value3}
                     Program 9: A program to demonstrate the creation of a dictionary.

                         Program9.py

                      File  Edit  Format   Run    Options   Window    Help

                      # Dictionary of student details
                      student = {
                          "name": "Aarav",
                          "age": 14,
                          "class": "VIII",
                          "section": "A"
                      }

                      print("Student Dictionary:", student)

                      # Dictionary of subject marks
                      marks = {
                          "Maths": 88,
                          "Science": 92,
                          "English": 85
                      }

                      print("Marks Dictionary:", marks)

                         Output

                      Student Dictionary: {'name': 'Aarav', 'age': 14, 'class': 'VIII', 'section': 'A'}
                      Marks Dictionary: {'Maths': 88, 'Science': 92, 'English': 85}

                     EMPTY DICTIONARY
                     You can create an empty dictionary using curly brackets or the dict() function.
                     Program 10: A program to create an empty dictionary.

                         Program10.py
                      File  Edit  Format   Run    Options   Window    Help

                      empty_dict = {}
                      print(empty_dict)

                      another_dict = dict()
                      print(another_dict)

                                                                                                  Tuples and Dictionary  137

| 134 135 136 137 138 139 140 141 142 143 144 |