AiTechWorlds
AiTechWorlds
Open your phone's contacts right now. When you want to call your friend Maya, you don't scroll thinking "She's contact number 47." You type her name and her number appears instantly.
That's because contacts are stored with labels — a name pointing to a phone number, an email, an address. The label (name) is what lets you find things quickly, not the position.
This is exactly what a Python dictionary does. Instead of accessing data by position (like a list), you access it by a meaningful key. The key can be a name, a word, a code — anything that makes sense for your data.
Why dictionaries? Lists are great for ordered sequences of similar items. But when your data has natural labels — like a person's name connecting to their details — dictionaries make your code clearer, faster, and much more intuitive.
A dictionary is a collection of key-value pairs. Think of it like a real-world dictionary: the word (key) maps to its definition (value).
# Empty dictionary
contact = {}
# Dictionary with data
person = {
"name": "Alice",
"age": 28,
"city": "New York"
}
# Dictionary with mixed value types
profile = {
"username": "alice_code",
"score": 4250,
"is_premium": True,
"badges": ["Python", "SQL", "Git"]
}
Line by line:
{} — curly braces define a dictionary (contrast with [] for lists)"name": "Alice" — a key-value pair; the colon separates key from value[]person = {"name": "Alice", "age": 28, "city": "New York"}
print(person["name"]) # Alice
print(person["age"]) # 28
This works perfectly — unless the key doesn't exist. Then Python raises a KeyError and your program crashes.
.get()person = {"name": "Alice", "age": 28}
# Returns None if key doesn't exist (no crash)
print(person.get("city")) # None
# Returns a default value if key doesn't exist
print(person.get("city", "Unknown")) # Unknown
print(person.get("age", 0)) # 28 (key exists, returns actual value)
Best practice: Use
.get()when you're not certain a key exists. Use[]when you're absolutely sure — theKeyErrorwill alert you to a bug if the key is missing unexpectedly.
student = {"name": "Bob", "age": 19}
student["major"] = "Computer Science"
student["gpa"] = 3.5
print(student)
# {'name': 'Bob', 'age': 19, 'major': 'Computer Science', 'gpa': 3.5}
Simply assign to a new key — if it doesn't exist, Python creates it.
student["gpa"] = 3.7 # Overwrites the existing value
student["age"] = 20
print(student["gpa"]) # 3.7
student = {"name": "Bob", "age": 20, "temp_note": "remove this"}
# del — removes the key permanently
del student["temp_note"]
# pop() — removes and RETURNS the value
age = student.pop("age")
print(age) # 20
print(student) # {'name': 'Bob'}
scores = {"Math": 92, "English": 85, "Science": 78}
print(scores.keys()) # dict_keys(['Math', 'English', 'Science'])
print(scores.values()) # dict_values([92, 85, 78])
print(scores.items()) # dict_items([('Math', 92), ('English', 85), ('Science', 78)])
# Convert to lists if needed
subjects = list(scores.keys())
print(subjects) # ['Math', 'English', 'Science']
.update()base = {"name": "Alice", "age": 28}
extra = {"city": "Boston", "age": 29} # 'age' overlaps
base.update(extra)
print(base)
# {'name': 'Alice', 'age': 29, 'city': 'Boston'}
# Note: overlapping keys get the value from 'extra'
inconfig = {"debug": True, "version": "2.1"}
print("debug" in config) # True
print("author" in config) # False
print("debug" not in config) # False
grades = {"Alice": 92, "Bob": 85, "Charlie": 78}
# Iterate over keys (default)
for name in grades:
print(name)
# Iterate over values
for score in grades.values():
print(score)
# Iterate over key-value pairs — most useful
for name, score in grades.items():
print(f"{name}: {score}")
Output of the last loop:
Alice: 92
Bob: 85
Charlie: 78
A dictionary value can itself be a dictionary. This is perfect for representing complex, structured data — like a record in a database.
employee = {
"id": "E001",
"name": "Sarah",
"contact": {
"email": "sarah@company.com",
"phone": "555-1234"
},
"skills": ["Python", "SQL", "Excel"]
}
# Accessing nested data
print(employee["name"]) # Sarah
print(employee["contact"]["email"]) # sarah@company.com
print(employee["skills"][0]) # Python
Chain the square brackets to go deeper: outer_key → inner_key → index.
| Situation | Use a List | Use a Dictionary |
|---|---|---|
| Storing similar items in order | ✓ | |
| Accessing by position/index | ✓ | |
| Need labels for your data | ✓ | |
| Looking up by name/key | ✓ | |
| Representing a single record/object | ✓ | |
| Shopping cart items | ✓ | |
| Phone contact (name → number) | ✓ | |
| Monthly sales figures | ✓ | |
| Config settings | ✓ |
Rule of thumb: If you find yourself asking "What's at position 3?" — use a list. If you're asking "What's the value for this name/label?" — use a dictionary.
students = {
"Alice": {"age": 20, "grade": "A", "gpa": 3.8},
"Bob": {"age": 19, "grade": "B", "gpa": 3.2},
"Charlie": {"age": 21, "grade": "A", "gpa": 3.9}
}
# Display all students in a formatted table
print("=" * 40)
print(f"{'Name':<10} {'Age':<5} {'Grade':<7} {'GPA'}")
print("=" * 40)
for name, info in students.items():
print(f"{name:<10} {info['age']:<5} {info['grade']:<7} {info['gpa']}")
# Add a new student
students["Diana"] = {"age": 20, "grade": "B+", "gpa": 3.5}
print(f"\nTotal students: {len(students)}")
# Find students with GPA above 3.5
print("\nHonor Roll (GPA > 3.5):")
for name, info in students.items():
if info["gpa"] > 3.5:
print(f" {name}: {info['gpa']}")
Output:
========================================
Name Age Grade GPA
========================================
Alice 20 A 3.8
Bob 19 B 3.2
Charlie 21 A 3.9
Total students: 4
Honor Roll (GPA > 3.5):
Alice: 3.8
Charlie: 3.9
Breaking it down:
students.items() — gives us (name, info) pairs to unpack in the loopf"{name:<10}" — left-aligns the name in a field 10 characters wide (for neat columns)info['age'] — accesses the nested dictionary using the inner keystudents["Diana"] = {...} — adds a completely new student recordlen(students) — counts the number of keys (students)Dictionaries are perfect for counting things:
sentence = "the cat sat on the mat the cat"
word_count = {}
for word in sentence.split():
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count)
# {'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1}
Every unique word becomes a key; the count becomes its value. This pattern appears constantly in real Python code.
| Operation | Syntax | Notes |
|---|---|---|
| Create | {"key": value} | Curly braces |
| Access | d["key"] | Raises KeyError if missing |
| Safe access | d.get("key", default) | Returns default if missing |
| Add/update | d["key"] = value | Creates or overwrites |
| Delete | del d["key"] | Permanent removal |
| Delete + return | d.pop("key") | Returns deleted value |
| All keys | d.keys() | Returns view object |
| All values | d.values() | Returns view object |
| All pairs | d.items() | Returns (key, value) pairs |
| Key exists? | "key" in d | Returns True/False |
| Count entries | len(d) | Number of key-value pairs |
[] for fast access when the key is guaranteed to exist.get() for safe access when the key might be missing.items() is your best friend for iterating over key-value pairsNext up: String Methods — where you'll learn to chop, reshape, search, and format text with the precision of a word processor.
Get this course's notes on Telegram!
Free cheat sheets, summaries & practice exercises