Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 143 - 2615_KEC
P. 143

    REMOVING ELEMENTS FROM A DICTIONARY
                     Elements can be removed using del, pop(), or clear().

                     Program 14: A program to remove elements from a dictionary.
                         Program14.py

                      File  Edit  Format   Run    Options   Window    Help

                      # Creating a dictionary for student information
                      student = {
                          "id": 101,
                          "name": "Ravi",
                          "subject": "Math",
                          "marks": 85
                      }

                      # Printing the original dictionary
                      print("Original Dictionary:", student)

                      # Removing the 'marks' entry using pop()
                      student.pop("marks")

                      # Removing the 'subject' entry using del
                      del student["subject"]

                      # Printing the dictionary after removing elements
                      print("After Removing Elements:", student)

                      # Clearing the entire dictionary
                      student.clear()
                      print("After Clear:", student)

                         Output
                      Original Dictionary: {'id': 101, 'name': 'Ravi', 'subject': 'Math', 'marks': 85}
                      After Removing Elements: {'id': 101, 'name': 'Ravi'}
                      After Clear: {}

                          REVISIT

                       ▶   A tuple is an ordered collection of items, meaning the order in which the items are stored is important.
                       ▶   A tuple can store multiple values in a single variable.
                       ▶  An empty tuple is a tuple that does not contain any elements.
                       ▶  Accessing a tuple means retrieving its elements or values.
                       ▶  Tuples support both positive indexing and negative indexing, similar to lists.
                       ▶  A dictionary is a collection that stores data in the form of key-value pairs.
                       ▶  A dictionary is enclosed in curly braces {}, with each key-value pair separated by a colon [:].

                                                                                                  Tuples and Dictionary  141

| 138 139 140 141 142 143 144 145 146 147 148 |