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 18, 2025
2.1k79

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

person = {"name": "Tom", "age": 25, "city": "Austin"}

Get values (safe vs unsafe)

Unsafe (can crash if key missing):

# print(person["email"])  # KeyError

Safe:

print(person.get("email", "N/A"))

Add/update

person["age"] = 26
person["email"] = "tom@example.com"

Loop patterns

for key in person:
    print(key, person[key])

for k, v in person.items():
    print(k, v)

Real use case: counting

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

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