Python Dictionary Tutorial

A dictionary is a collection containing pair(one is key and another is value) where insertion order is not preserved. It is changeable and indexed. Python dictionaries written with curly brackets.

car_detail={"brand":"Maruti","model":"Breeza","year":2019}

car_detail

Output: {'brand': 'Maruti', 'model': 'Breeza', 'year': 2019}

#Accessing items:

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

#get the value of "brand" key

car_detail["brand"]
Output: 'Maruti'
#change the value of a specific item by referring to its key name:
car_detail["year"]=2018
car_detail
Output: {'brand': 'Maruti', 'model': 'Breeza', 'year': 2018}
#Retrieving all pairs from dictionary
for i,j in car_detail.items():
print(i,j)
Output:
brand Maruti
model Breeza
year 2018
#find the length of dictionary : no.of pairs presnt in dictionary
len(car_detail)
Output: 3
#adding new pair
car_detail["color"]="Blue"
car_detail
Output: 
{'brand': 'Maruti', 'model': 'Breeza', 'year': 2018, 'color': 'Blue'}
#Remove a pair using pop() from dictionary
car_detail.pop("year")
car_detail
Output: 
{'brand': 'Maruti', 'model': 'Breeza', 'color': 'Blue'}
#remove a pair using popitem() from dictionary
car_detail.popitem()
car_detail
Output: 
{'brand': 'Maruti', 'model': 'Breeza'}

The method popitem() removes the last inserted item


#del keyword removes the item with the specified key name
del car_detail["brand"]
car_detail
Output: 
{'model': 'Breeza'}

#consider another dictionary
student_detail={"regdno":101,"name":"Sanghamitra","branch":"CSE"}
student_detail
Output: 
{'regdno': 101, 'name': 'Sanghamitra', 'branch': 'CSE'}
#copy a dictionary using copy()
student=student_detail.copy()
student
Output: 
{'regdno': 101, 'name': 'Sanghamitra', 'branch': 'CSE'}	

#clear all pair from dictionary using clear()
student.clear()
student
Output: {}
#Another approach to create a dictionary using dict() constructor
my_dictionary=dict(brand="Honda",model="Honda City",color="Red")
my_dictionary
Output: 
{'brand': 'Honda', 'model': 'Honda City', 'color': 'Red'}


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext