Cyber Services / All lessons / Python Programming / Dictionaries

Dictionaries

Module 14 of 31 · 4 min read · Free to read

MODULES ↓ Command blocks have a COPY button
Key-Value Data Structures

What Are Dictionaries?

A dictionary (dict) is Python’s built-in **key-value store**—an unordered, mutable collection where each item is a pair: a key (unique, immutable) and a value (any type).

  • Keys must be hashable: strings, numbers, tuples (not lists or dicts).
  • Values can be anything: numbers, strings, lists, even other dictionaries.
  • Fast lookups: O(1) average time for accessing, inserting, or deleting by key.
  • Mutable: You can add, update, or remove items after creation.

Dictionaries power real-world applications: user profiles, configuration settings, caches, JSON data, and more.

Creating Dictionaries

# Empty dictionary
empty = {}

# Literal syntax
student = {"name": "Ali", "age": 22, "grade": "A"}

# Using dict() constructor
person = dict(name="Sara", city="Dubai", active=True)

# From lists of tuples
pairs = [("a", 1), ("b", 2)]
d = dict(pairs)  # {'a': 1, 'b': 2}

Essential Dictionary Operations

1. Access Value by Key
user = {"name": "Omar", "role": "admin"}
print(user["name"])  # Omar

# ❌ KeyError if key missing:
# print(user["email"])
2. Safe Access with .get()
user = {"name": "Omar"}
email = user.get("email", "Not provided")
print(email)  # Not provided

# Without default → returns None
role = user.get("role")
print(role)  # None
3. Add or Update Item
config = {"debug": False}
config["host"] = "localhost"    # add new
config["debug"] = True          # update existing
print(config)  # {'debug': True, 'host': 'localhost'}
4. Remove Item with del
data = {"temp": 25, "unit": "C"}
del data["unit"]
print(data)  # {'temp': 25}
5. Remove & Return with .pop()
inventory = {"apple": 10, "banana": 5}
count = inventory.pop("apple")
print(count)      # 10
print(inventory)  # {'banana': 5}

# With default (avoids KeyError)
orange = inventory.pop("orange", 0)
print(orange)     # 0
6. Check if Key Exists
settings = {"theme": "dark", "lang": "en"}
if "theme" in settings:
    print("Theme is set!")

# ❌ Don't do this: if settings["theme"]: → fails if missing!

Built-in Dictionary Methods

7. Get All Keys
user = {"name": "Ali", "age": 25}
keys = user.keys()
print(list(keys))  # ['name', 'age']
8. Get All Values
grades = {"math": 90, "science": 85}
values = grades.values()
print(list(values))  # [90, 85]
9. Get Key-Value Pairs
person = {"name": "Sara", "city": "Abu Dhabi"}
items = person.items()
for key, value in items:
    print(f"{key}: {value}")
# name: Sara
# city: Abu Dhabi
10. Update Dictionary
base = {"host": "localhost", "port": 80}
updates = {"port": 443, "ssl": True}
base.update(updates)
print(base)  # {'host': 'localhost', 'port': 443, 'ssl': True}
11. Clear All Items
cache = {"temp": 30, "humidity": 60}
cache.clear()
print(cache)  # {}
12. Create Copy (Shallow)
original = {"name": "Ali", "scores": [85, 90]}
copy = original.copy()
copy["name"] = "Omar"
print(original["name"])  # Ali (unchanged)

# ⚠️ But nested objects are shared!
copy["scores"].append(95)
print(original["scores"])  # [85, 90, 95] ← modified!

Advanced & Practical Examples

13. Default Values with setdefault()
visits = {}
user = "Ali"
visits.setdefault(user, 0)  # sets to 0 if not exists
visits[user] += 1
print(visits)  # {'Ali': 1}
14. Dictionary Comprehension
# Square numbers as values
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Filter even keys
even_squares = {k: v for k, v in squares.items() if k % 2 == 0}
print(even_squares)  # {2: 4, 4: 16}
15. Nested Dictionaries (Real-World Data)
school = {
    "CS101": {
        "title": "Intro to Python",
        "instructor": "Dr. Mubasher",
        "students": ["Ali", "Sara"]
    },
    "MATH201": {
        "title": "Calculus",
        "instructor": "Prof. Ahmed",
        "students": ["Omar"]
    }
}
print(school["CS101"]["instructor"])  # Dr. Mubasher
16. Count Frequencies (Manual)
text = "hello"
freq = {}
for char in text:
    freq[char] = freq.get(char, 0) + 1
print(freq)  # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
17. Merge Dictionaries (Python 3.9+)
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
merged = a | b  # y from b overwrites a
print(merged)  # {'x': 1, 'y': 3, 'z': 4}
18. Get with Default Factory (defaultdict)
from collections import defaultdict

# Automatically creates missing keys with default type
counts = defaultdict(int)  # int() → 0
counts["apples"] += 1
print(counts["oranges"])  # 0 (no KeyError!)
19. Sort Dictionary by Key or Value
data = {"banana": 3, "apple": 5, "cherry": 2}

# By key
sorted_by_key = dict(sorted(data.items()))
print(sorted_by_key)  # {'apple': 5, 'banana': 3, 'cherry': 2}

# By value
sorted_by_val = dict(sorted(data.items(), key=lambda x: x[1]))
print(sorted_by_val)  # {'cherry': 2, 'banana': 3, 'apple': 5}
20. JSON-Like Data Processing
import json
# Dictionaries map directly to JSON objects
user_data = {
    "id": 101,
    "name": "Ali",
    "preferences": {"theme": "dark", "notifications": True}
}
json_str = json.dumps(user_data, indent=2)
print(json_str)  # Valid JSON string

Common Pitfalls & Best Practices

  • ✅ **Always check key existence** before accessing (use in or .get()).
  • ✅ **Use meaningful keys**—prefer strings like "student_id" over vague names.
  • ⚠️ **Avoid mutable keys**—lists or dicts cannot be dictionary keys.
  • ✅ **Prefer .get()** over direct access when key might be missing.
  • ✅ **Use dictionary comprehensions** for clean, readable transformations.
  • ⚠️ **Remember: .copy() is shallow**—use copy.deepcopy() for nested structures.

Key Takeaways

  • Dictionaries are **fast, flexible key-value stores**.
  • Keys must be **immutable and unique**; values can be **anything**.
  • Use **built-in methods** (.keys(), .values(), .items(), .get(), .pop()) for safe, efficient operations.
  • They are the **foundation of structured data** in Python—used in APIs, configs, databases, and more.
  • Master dictionaries to unlock **real-world data processing** capabilities.
Modules (31) ← Python Programming