Page 107 - tp_Modula_v2.0
P. 107

REMOVING OR DELETING ELEMENTS OF A DICTIONARY

                 As you know, the pop( ) method is used to remove the dictionary element with the specified
                 key. The clear( ) method is used to remove all the elements of a dictionary and the popitem( )
                 method is used to remove any element from the Python dictionary. The del method is used to
                 delete a specific element or entire dictionary.

                     SOME MORE PROGRAMS

                 Program 6: To remove or delete elements from a dictionary.
                     Program6.py
                  File  Edit  Format  Run   Options   Window    Help

                  dict1={'Name': 'A', 'Rollno': 1, 'Marks':[10, 20, 30], 'Mobile': 9876754534}
                  print(dict1)
                  print(dict1.pop('Rollno'))
                  print(dict1)
                  print(dict1.popitem())
                  print(dict1)
                  print(dict1.clear())


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

                     Output

                  {'Name': 'A', 'Rollno': 1, 'Marks': [10, 20, 30], 'Mobile': 9876754534}
                  1
                  {'Name': 'A', 'Marks': [10, 20, 30], 'Mobile': 9876754534}
                  ('Mobile', 9876754534)
                  {'Name': 'A', 'Marks': [10, 20, 30]}
                  None



                 Program 7: To convert dictionary to list of tuples.

                     Program7.py
                  File  Edit  Format  Run   Options   Window    Help
                  Fruits = {"Apple" : 1, "Mango" : 2, "Banana" : 4}
                  items = list(Fruits.items())
                  for item in items:
                      print(len(item), item)


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

                     Output

                  2 ('Apple', 1)
                  2 ('Mango', 2)
                  2 ('Banana', 4)










                                                                                           Dictionary in Python   105
   102   103   104   105   106   107   108   109   110   111   112