HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Python Dictionary


Dictionary is unordered,changable and indexed collection of items.


Create a Dictionary


In Python,dictionaries are written with curly brackets and they have keys and values pair.

Example
  thisdict={
 "brand":"Ford",
  "model":"Mustang",
  "year":1964
    
    }
 print(thisdict) 
 
 Output
 {'brand','Ford','model','Mustang','year','1964'}
              

Access Dictionary Elements


We can access the items of a dictionary by referring to its key name,inside square brackets.


Example
  thisdict={
        "brand":"Ford",
        "model":"Mustang",
        "year":1964
    
    }
    print(thisdict["model"])   
 
 Output
 {'brand','Ford','model','Mustang','year','1964'}
              

Loop through Dictionary


We can loop through the dictionary items by using a for loop.


When looping through dictionary the return values are the keys of dictionary,but there are methods to return the values as well.


Example
  thisdict={
        "brand":"Ford",
        "model":"Mustang",
        "year":1964
    
    }
    for x in thisdict:
        print(x)   
 
 Output
 {'brand','Ford','model','Mustang','year','1964'}
              
  • We can also use the values() function to return values of a dictionary.

  • Example
     thisdict={
            "brand":"Ford",
            "model":"Mustang",
            "year":1964
        
        }
        for x in thisdict.values():
            print(x)   
     
     Output
     {'brand','Ford','model','Mustang','year','1964'}
                  

    Loop through both keys and values using the items() function.


    Example
       thisdict={
            "brand":"Ford",
            "model":"Mustang",
            "year":1964
        
        }
        for x,y in thisdict.values():
            print(x,y) 
     
     Output
     {'brand','Ford','model','Mustang','year','1964'}
                  

    Dictionary Length


    To determine how many items a dictionary has, use the len() function.

    Example
      thisdict={
             "brand":"Ford",
             "model":"Mustang",
             "year":1964
        
        }
       print(len(thisdict))
     
     Output
     {'brand','Ford','model','Mustang','year','1964'}
                  

    Add Items in Dictionary