Python | Dictionary Function and Methods



Python | Dictionary Function and Methods


Dictionary length

len() using you will get length of Dictionary

Example


    dictionary = {
          "Fname": "neel",
          "Sname": "patel",
          "Year":  1999 
    }

    print(len(dictionary))


 Output

    3



Change Items in Dictionary

you can specific value change in dictionary by using that key


Example

    dictionary = {
          "Fname": "neel",
          "Sname": "patel",
          "Year":  1999 
    }

    dictionary["Year"]=2018
    print(dictionary)


 Output

    {'Fname': 'neel', 'Sname': 'patel', 'Year': 2018}





You can also used update() Method for change the value

Example

    dictionary = {
          "Fname": "neel",
          "Sname": "patel",
          "Year":  1999 
    }
    dictionary.update({"Year": 2018})

    print(dictionary)

    
 Output

    {'Fname': 'neel', 'Sname': 'patel', 'Year': 2018}



Remove Items from Dictionary

pop() Method

pop() methods is used for removed specific items from dictionary based on that's key 

Example

    dictionary = {
      "Fname": "neel",
      "Sname": "patel",
      "Year":  1999 
    }

    dictionary.pop("Year")

    print(dictionary)

Output

    {'Fname': 'neel', 'Sname': 'patel'}


popitem() Method

popitem() methods is used for  removes the last item inserted in dictionary
  

Example

    dictionary = {
      "Fname": "neel",
      "Sname": "patel",
      "Year":  1999 
    }

    dictionary.pop("Year")

    print(dictionary)

Output

    {'Fname': 'neel', 'Sname': 'patel'}


'del' keyword

the 'del' keyword removes the specific item from dictionary based on that's key

Example

    dictionary = {
      "Fname": "neel",
      "Sname": "patel",
      "Year":  1999 
    }

    del dictionary["Sname"]    

    print(dictionary)

Output

    {'Fname': 'neel', 'Year': 1999}


'del' Keyword also removes delete dictionary completely

Example

    dictionary = {
      "Fname": "neel",
      "Sname": "patel",
      "Year":  1999 
    }

    del dictionary     

    print(dictionary)


Output  

        Traceback (most recent call last):
        File "./prog.py", line 8, in <module>     
        NameError: name 'dictionary' is not defined


clear() Method

clear() method return empties dictionary

Example

    dictionary = {
      "Fname": "neel",
      "Sname": "patel",
      "Year":  1999 
    }

   dictionary.clear()     

   print(dictionary)

Output  

  {}

Post a Comment (0)
Previous Post Next Post