Topic 14: Dictionary Data Type in Python
In Python, a dictionary is one of the most powerful and flexible data types. It allows you to store data in key–value pairs, just like a real-world dictionary where words (keys) have meanings (values). Dictionaries are unordered, mutable, and indexed by unique keys, making them ideal for quick lookups and data organization.
Syntax of Dictionary
# Creating a dictionary
my_dict = {
"name": "Alice",
"age": 25,
"city": "Delhi"
}
-
Keys: Must be unique and immutable (e.g., strings, numbers, tuples).
-
Values: Can be of any data type (string, list, number, etc.).
Creating a Dictionary
1️⃣ Using Curly Braces {}
student = {"name": "John", "roll_no": 101, "course": "B.Tech"}
2️⃣ Using dict() Constructor
student = dict(name="John", roll_no=101, course="B.Tech")
Accessing Dictionary Elements
You can access values using their key names.
student = {"name": "John", "roll_no": 101, "course": "B.Tech"}
print(student["name"]) # Output: John
print(student.get("course")) # Output: B.Tech
Adding and Updating Elements
student["city"] = "Meerut" # Add new key-value pair
student["course"] = "M.Tech" # Update existing value
print(student)
Removing Elements
student.pop("roll_no") # Removes a specific key
student.popitem() # Removes the last inserted item
del student["name"] # Deletes a key-value pair
student.clear() # Clears entire dictionary
Common Dictionary Functions
| Function | Description | Example |
|---|---|---|
len() |
Returns the number of items | len(student) |
keys() |
Returns all keys | student.keys() |
values() |
Returns all values | student.values() |
items() |
Returns all key-value pairs | student.items() |
update() |
Updates with another dictionary | student.update({"marks": 90}) |
copy() |
Returns a shallow copy | new_dict = student.copy() |
Looping Through Dictionary
student = {"name": "John", "marks": 90, "grade": "A"}
# Loop through keys
for key in student:
print(key, ":", student[key])
Output:
name : John
marks : 90
grade : A
Flowchart: Working of Dictionary
![]() |
| Dictionary data type |
Example Program
# Dictionary Example Program
employee = {
"name": "Rahul",
"department": "IT",
"salary": 50000
}
print("Employee Name:", employee["name"])
employee["salary"] = 55000
employee["location"] = "Mumbai"
print("Updated Employee Record:", employee)
Output:
Employee Name: Rahul
Updated Employee Record: {'name': 'Rahul', 'department': 'IT', 'salary': 55000, 'location': 'Mumbai'}
Advantages of Dictionary
- Fast lookups and modifications
- Flexible data storage
- Easy to merge and manipulate
- Ideal for real-world mapping (like student details, employee data, etc.)
Conclusion
Python dictionaries are an essential part of Python programming. They help store, organize, and access data efficiently using key-value pairs. Once you master dictionaries, you can handle complex data and structures in Python easily!

Comments
Post a Comment