Thursday, November 13, 2025

Dictionary in python

What is a Dictionary in Python? 

 A dictionary in Python is a data structure that stores data in key–value pairs. It is unordered, mutable, and does not allow duplicate keys. 

 Think of it like a real dictionary:

 You look up a word (key) 
 You get its meaning (value) 

 ✅ Syntax my_dict = { "key1": "value1", "key2": "value2", } 


 πŸ“Œ Basic Example 
student = { "name": "Raghav", "age": 20, "course": "Computer Science" }
 print(student) 
 Output: {'name': 'Raghav', 'age': 20, 'course': 'Computer Science'} 

 πŸ“Œ Accessing Values print(student["name"])
 print(student["age"]) 

 πŸ“Œ Adding a New Key–Value Pair 

student["grade"] = "A" print(student) 

 πŸ“Œ Updating a Value 

student["age"] = 21 

 πŸ“Œ Deleting an Item 

del student["course"] OR student.pop("course") 


 πŸ“Œ Looping Through Dictionary 

for key, value in student.items(): 
 print(key, ":", value) 


 πŸ“Œ Dictionary Inside Dictionary (Nested Dictionary) 

college = { "student1": {"name": "Raghav", "age": 20}, "student2": {"name": "Aman", "age": 22} } print(college["student1"]["name"])

No comments:

Post a Comment

Python Viva Questions

  Basic Python Viva Questions 1. What is Python? Python is a high-level, interpreted, and object-oriented programming language used for w...