A dictionary in Python is a collection of key-value pairs.
✅ It's like a real-life dictionary – you look up a word (key) to find its definition (value).
Feature | Description |
---|---|
Key-Value Pairs | Each item is a pair: key: value |
Unordered | Python 3.6+: preserves insertion order |
Mutable | Can change, add, or remove items |
Indexed by Keys | Access values using keys, not indices |
No Duplicates | Keys must be unique |
# Using curly braces
student = {"name": "Abhi", "age": 25, "grade": "A"}
# Using dict() constructor
employee = dict(id=101, dept="HR", active=True)
print(student["name"]) # Output: Abhi
print(student.get("age")) # Output: 25
🔸
.get()
is safer – returnsNone
if key doesn't exist (no error).
student["age"] = 26 # Modify
student["gender"] = "Male" # Add new key-value pair
student.pop("grade") # Remove by key
student.popitem() # Remove last item
del student["name"] # Delete by key
student.clear() # Remove all items
for key in student:
print(key, student[key])
for key, value in student.items():
print(key, "=>", value)
Method | Description |
---|---|
keys() |
Returns all keys |
values() |
Returns all values |
items() |
Returns key-value pairs as tuples |
update() |
Merges another dictionary |
get(key) |
Returns value of the key or None |
students = {
"101": {"name": "Alice", "marks": 85},
"102": {"name": "Bob", "marks": 90}
}
print(students["102"]["name"]) # Output: Bob
A dictionary is like a contact list:
Name (key) → Phone number (value)
Each contact is unique, and you use the name to fetch the number.
Dictionaries store key-value pairs.
Keys must be unique and immutable.
Great for structured data like JSON, user profiles, records, etc.