Data Structures18 min read

Dict Fundamentals

Master dictionaries as key-value maps: safe lookups, updating values, looping patterns, and real-world use cases like configs and counters.

David Miller
December 21, 2025
0.0k0

A **dictionary (dict)** stores data as **key -> value**. You use dict when you want: - fast lookup by key - mapping IDs to objects - configuration settings - counting occurrences ## Create a dict ```python person = {"name": "Tom", "age": 25, "city": "Austin"} ``` ## Get values (safe vs unsafe) Unsafe (can crash if key missing): ```python # print(person["email"]) # KeyError ``` Safe: ```python print(person.get("email", "N/A")) ``` ## Add/update ```python person["age"] = 26 person["email"] = "tom@example.com" ``` ## Loop patterns ```python for key in person: print(key, person[key]) for k, v in person.items(): print(k, v) ``` ## Real use case: counting ```python text = "banana" count = {} for ch in text: count[ch] = count.get(ch, 0) + 1 print(count) # {'b':1,'a':3,'n':2} ``` ## Graph: dict mental model ```mermaid flowchart LR A[key: name] --> B[value: Tom] C[key: age] --> D[value: 25] ``` ## Remember - dict gives fast key lookups - use get() to avoid KeyError - items() is best for looping key+value

#Python#Beginner#Dictionary