Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 141 - 2615_KEC
P. 141

    Program 12: A program to modify elements of a dictionary.

                         Program12.py

                      File  Edit  Format   Run    Options   Window    Help

                      # Creating a dictionary called 'product'
                      product = {
                          "item": "Smartphone",
                          "brand": "TechX",
                          "price": 20000
                      }

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

                      # Modifying an existing value
                      product["price"] = 25000

                      # Adding a new key–value pair
                      product["colour"] = "Black"

                      # Printing the updated dictionary
                      print("Updated Dictionary:", product)

                         Output

                      Original Dictionary: {'item': 'Smartphone', 'brand': 'TechX', 'price': 20000}
                      Updated  Dictionary:  {'item':  'Smartphone', 'brand':  'TechX',  'price':  25000,
                      'colour': 'Black'}

                     DICTIONARY METHODS

                     Python provides various built-in dictionary methods. The following table describes explanation of
                     these methods.

                          Method                                          Explanation
                     keys()              Returns a view of all the keys in the dictionary.

                     values()            Returns a view of all the values in the dictionary.
                     items()             Returns a view of all the key-value pairs in the dictionary as tuples.

                                         Returns the value for the specified key. If the key doesn't exist, it returns None
                     get(key)
                                         or a default value.
                                         Updates  the  dictionary  with  key-value  pairs  from  another  dictionary  or
                     update([other])
                                         iterable.
                                         Removes and returns the value of the specified key. If the key doesn't exist, it
                     pop(key)
                                         raises a KeyError.

                                                                                                  Tuples and Dictionary  139

| 136 137 138 139 140 141 142 143 144 145 146 |