What is a Dictionary?
# Syntax
my_dict = {
"key1": "value1",
"key2": "value2"
}
Example:
student = {
"name": "Alice",
"age": 22,
"course": "Computer Science"
}
Dictionary Basics
1. Accessing Values
print(student["name"]) # Output: Alice
You can also use .get()
which avoids an error if the key doesn't exist:
print(student.get("email", "Not Found")) # Output: Not Found
2. Modifying Values
student["age"] = 23
3. Adding New Key-Value Pair
student["email"] = "alice@example.com"
4. Removing Elements
student.pop("course") # Removes 'course' key
🔹 Dictionary Methods
Method | Description |
---|---|
dict.keys() |
Returns all keys |
dict.values() |
Returns all values |
dict.items() |
Returns key-value pairs |
dict.update({...}) |
Updates dictionary with new pairs |
dict.pop(key) |
Removes the item with the given key |
dict.clear() |
Removes all items |
Example:
print(student.keys()) # dict_keys(['name', 'age', 'email'])
print(student.values()) # dict_values(['Alice', 23, 'alice@example.com'])
print(student.items()) # dict_items([('name', 'Alice'), ...])
Dictionary Types (Based on Structure)
1. Nested Dictionary
A dictionary inside another dictionary.
students = {
"101": {"name": "Alice", "age": 22},
"102": {"name": "Bob", "age": 24}
}
print(students["101"]["name"]) # Output: Alice
2. Empty Dictionary
empty_dict = {}
3. Using dict()
Constructor
data = dict(name="John", age=30)
print(data) # {'name': 'John', 'age': 30}
4. Dictionary with Mixed Data Types
info = {
"name": "Alice",
"age": 25,
"marks": [85, 90, 92],
"is_graduated": True
}
5. Dictionary with Tuple Keys
Keys must be immutable — so tuples are allowed.
location = {
(10.4, 20.3): "Point A",
(11.5, 22.1): "Point B"
}
Looping Through a Dictionary
for key, value in student.items():
print(f"{key}: {value}")
Dictionary Comprehension
squares = {x: x*x for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Summary Table
Feature | Syntax/Example |
---|---|
Create | d = {"a": 1, "b": 2} |
Access | d["a"] or d.get("a") |
Add/Update | d["c"] = 3 |
Delete | d.pop("a") or del d["a"] |
Loop | for k, v in d.items() |
Keys / Values / Items | d.keys() , d.values() , d.items() |
Nested Dictionary | d = {"outer": {"inner": "value"}} |
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.