Page 105 - tp_Modula_v2.0
P. 105

Method                                       Explanation
                     clear( )                           Removes all the elements

                     copy( )                            Creates a shallow copy
                     items( )                           Returns a new view of dictionary items

                     keys( )                            Returns a new view of dictionary keys
                     update([other])                    Updates the dictionary with the specified key and value

                     get(key)                           Returns the value of key

                 Program 3: To perform various built-in dictionary methods.

                     Program3.py
                  File  Edit  Format  Run   Options   Window    Help

                  sample_dict = {"name": "John", "age": 30, "city": "New York"}
                  sample_dict.pop("age")
                  print("After pop:", sample_dict)

                  sample_dict.popitem()
                  print("After popitem:", sample_dict)

                  sample_dict.clear()
                  print("After clear:", sample_dict)

                  # Reset dictionary
                  sample_dict = {"name": "John", "age": 30, "city": "New York"}

                  copied_dict = sample_dict.copy()
                  print("Copy:", copied_dict)

                  print("Items:", sample_dict.items())
                  print("Keys:", sample_dict.keys())

                  sample_dict.update({"country": "USA"})
                  print("After update:", sample_dict)

                  print("Get 'city':", sample_dict.get("city"))


                 On running the above program, you will get the following output:

                     Output

                  After pop: {'name': 'John', 'city': 'New York'}
                  After popitem: {'name': 'John'}
                  After clear: {}
                  Copy: {'name': 'John', 'age': 30, 'city': 'New York'}
                  Items: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
                  Keys: dict_keys(['name', 'age', 'city'])
                  After update: {'name': 'John', 'age': 30, 'city': 'New York', 'country':
                  'USA'}
                  Get 'city': New York





                                                                                           Dictionary in Python   103
   100   101   102   103   104   105   106   107   108   109   110