Python for beginners- Dictionary Operations

 Dictionary is one of the type of collections in python. It combines variety of data items under a common name.

Syntax be like,

 Name={

              "Membername1":"Value",

              "Membername2":"Value",

               ........................................

              "Membernamen":"Value"

             }

An example is given below...

Eg:

Creating a dictionary named "sunglass"

 sunglass = {

                      "brand": "Suntrack"

                      "model": "Wideangle"

                      "Year " : "2023"

                     }

To print the dictionary, use the below code.

print(sunglass)

It displays the output as follows.

{'brand': 'Suntrack', 'model':'Wideangle','Year':'2023'}

The operations on the dictionary are

  • get()
          This method is used to get a value from dictionary. For getting a value from above example, the              following code is used.
          print(sunglass.get("model")) -This displays Wideangle          
  • keys()
          keys are the members in the dictionary. This method is useful to get the keys in the dictionary.

           sunglass = {"brand": "Suntrack", "model": "Wideangle" , "Year " : "2023" }
           sunglass.keys()
         
           When you execute this, you will get the below output.
            dict_keys(['brand','model','Year'])     
  • values()
           These are the data assigned to the keys. To get the values assigned for the keys, use the below                 code.
           sunglass = {"brand": "Suntrack", "model": "Wideangle", "Year ": "2023"}
           sunglass.values()
           The output is
                 dict_values(['Suntrack','Wideangle','2023'])    
  • copy()
           This method is used to copy a value to another variable. For eg,
            sunglass = {"brand": "Suntrack", "model": "Wideangle" , "Year " : "2023" }
            a=sunglass.copy()
            print(a)
           when you run this code, you get the copied value.
            {'brand': 'Suntrack', 'model':'Wideangle','Year':'2023'}
  • pop()
          This method is used to extract a value from the dictionary.
           sunglass = {"brand": "Suntrack", "model": "Wideangle" , "Year " : "2023" }
           sunglass.pop("Year")
           It gives you the year value as output.
           '2023'
  • clear()

             Do you want to empty the dictionary, use this method.

              sunglass = {"brand":"Suntrack","model": "Wideangle","Year ": "2023"}

              sunglass.clear()
              print(sunglass)

              It clears all the data in the sunglass dictionary. The output is {}

         These are operations performed for Dictionary.


 

No comments:

Post a Comment