Dictionaries in Python
Dictionaries are one of the most powerful and commonly used data structures in Python. They store data in the form of key-value pairs, making them perfect for representing structured information like user profiles, product information, API responses, and configuration settings.
A dictionary is mutable, unordered (Python 3.7+ maintains insertion order), and highly optimized for fast lookup.
What Is a Dictionary?
A dictionary stores information in pairs, where:
- Key → A unique identifier
- Value → The information associated with that key
Dictionaries use { } curly brackets.
student = {
"name": "Sreekanth",
"age": 25,
"country": "USA"
}
Dictionaries allow you to structure real-world data in a clean way.
Why Use Dictionaries?
Dictionaries are extremely useful because:
- They store information in a structured way
- Fast access using keys (O(1) time)
- Keys are easy to remember
- Values can be any data type (lists, tuples, other dictionaries)
- Data can be updated without recreating the entire structure
Creating Dictionaries
person = {"name": "John", "age": 30}
empty_dict = {} # empty dictionary
details = dict(name="Alice", age=22) # using dict()
Accessing Dictionary Values
You can access values by using keys inside square brackets or using the get() method.
student = {"name": "Sreekanth", "age": 25}
print(student["name"]) # Sreekanth
print(student.get("age")) # 25
Using get() is safer because it does not throw an error if a key doesn't exist.
Modifying Dictionary Values
Dictionaries are mutable, so values can be changed easily.
student = {"name": "Sreekanth", "age": 25}
student["age"] = 26 # updating value
student["country"] = "USA" # adding new key-value pair
print(student)
Removing Items From a Dictionary
| Method | Description |
|---|---|
pop(key) | Removes key and returns its value |
popitem() | Removes last inserted item |
del dict[key] | Deletes a specific key |
clear() | Removes all items |
data = {"a": 1, "b": 2, "c": 3}
data.pop("b") # removes key 'b'
data.popitem() # removes last item
del data["a"] # removes key 'a'
data.clear() # empty dictionary
Looping Through a Dictionary
You can loop through keys, values, or both.
info = {"name": "Sree", "age": 25}
for key in info:
print(key, info[key]) # key and value
for value in info.values():
print(value)
for key, value in info.items():
print(key, "=", value)
Checking if a Key Exists
product = {"id": 101, "name": "Laptop"}
if "name" in product:
print("Key found!")
Nested Dictionaries
Dictionaries inside dictionaries are commonly used to store complex structured data (like JSON).
student = {
"name": "Sree",
"marks": {"math": 90, "science": 95, "english": 88}
}
print(student["marks"]["science"]) # 95
Real-World Example: JSON-like API Response
user = {
"id": 101,
"username": "dataplexa",
"profile": {
"followers": 1200,
"following": 300
}
}
print(user["profile"]["followers"])
Real-World Example: Product Information
product = {
"name": "Wireless Mouse",
"price": 799,
"stock": 25
}
print("Product:", product["name"])
print("Price:", product["price"])
📝 Practice Exercises
- Create a dictionary of 3 students with keys
name,age, andgrade. - Write a program to update the price of a product stored in a dictionary.
- Check whether a key
"email"exists in a dictionary. - Create a nested dictionary representing departments and employee counts.
- Loop through a dictionary and print all key-value pairs in a clean format.
✅ Practice Answers
Answer 1:
student = {"name": "Ravi", "age": 20, "grade": "A"}
print(student)
Answer 2:
product = {"name": "Keyboard", "price": 1200}
product["price"] = 999
print(product)
Answer 3:
data = {"user": "Sree", "age": 25}
if "email" in data:
print("Exists")
else:
print("Not found")
Answer 4:
departments = {
"IT": 10,
"HR": 5,
"Finance": 7
}
print(departments)
Answer 5:
info = {"name": "Sree", "country": "USA"}
for k, v in info.items():
print(k, "=", v)