C
Python/Intro/Lesson 07

dict — The Standard for Key-Value Storage

15 min·theory
This chapter
6/7

dict — The Standard for Key-Value Storage

🎯 After Reading This Lesson

After finishing this lesson, you will be able to confidently do the following 3 things.

  • ✅ dict key requirements + collision handling
  • ✅ Four methods: get · setdefault · pop · update
  • ✅ dict comprehension + dict merging (PEP 584)

Keep the learning objectives as a checklist — close the lesson once you can answer all of them.

7 dict Patterns — Code + Execution Results

dict = key:value pairs. Fast lookup by name → value (lookup O(1)). Equivalent to Map·HashMap·Object in other languages.


1. Creating

python
person = {"Name": "Hong Gil-dong", "Age": 28, "Occupation": "Developer"}
empty_dict = {}
print(type(person))         # <class 'dict'>
print(len(person))          # 3 (number of keys)

{ key: value, key: value } — colon separates pairs, comma separates items.


2. Accessing Values

python
person = {"Name": "Hong Gil-dong", "Age": 28}

print(person["Name"])       # Hong Gil-dong
print(person["Age"])       # 28

# ⚠️ Missing keys raise KeyError
# print(person["Height"])       # KeyError: 'Height'

# Safe access — get()
print(person.get("Height"))     # None (no error)
print(person.get("Height", 0))  # 0 (default value)

3. Adding · Updating · Deleting

python
person = {"Name": "Hong Gil-dong"}

person["Age"] = 28              # Add new key
person["Name"] = "Lee Mong-ryong"        # Update existing key

del person["Age"]
print(person)                    # {'Name': 'Lee Mong-ryong'}

4. Checking Existence — in

python
person = {"Name": "Hong Gil-dong", "Age": 28}

if "Name" in person:
    print("Name exists")

if "Height" not in person:
    print("Height does not exist")

in on a list checks values, but in on a dict checks keys.


5. Iteration (for)

python
person = {"Name": "Hong Gil-dong", "Age": 28, "Occupation": "Developer"}

# Keys only
for key in person:
    print(key)

# Keys + values together — used most often
for key, value in person.items():
    print(f"{key}: {value}")

# Values only
for value in person.values():
    print(value)

Execution result:

code
Name
Age
Occupation
Name: Hong Gil-dong
Age: 28
Occupation: Developer
Hong Gil-dong
28
Developer

6. Nested dict (Real-world Pattern)

python
company = {
    "Name": "CodeMaster",
    "Employees": [
        {"Name": "Hong Gil-dong", "Role": "Development"},
        {"Name": "Lee Mong-ryong", "Role": "Design"},
    ],
}

print(company["Employees"][0]["Name"])    # Hong Gil-dong
print(company["Employees"][1]["Role"])    # Design

company["Employees"].append({"Name": "Seong Chun-hyang", "Role": "Planning"})
print(len(company["Employees"]))          # 3

JSON and API responses look exactly like this — Python dicts are JSON-friendly.


7. Common Pattern — Counter

python
text = "apple pear apple persimmon apple pear"
words = text.split()

counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1

print(counts)                   # {'apple': 3, 'pear': 2, 'persimmon': 1}

get(key, 0) = "return the value if it exists, otherwise 0" — the core of counting and accumulation patterns.


list vs dict — When to Use Which?

listdict
Access method[numeric index]["key"]
OrderingYesYes (3.7+)
Lookup speedO(n)O(1)
Use caseGrouping multiple itemsLookup by name

One-line Summary

OperationSyntax
Create{"key": "value"}
Accessd["key"] / d.get("key", default)
Add · Updated["key"] = value
Deletedel d["key"]
Check existence"key" in d
Iteratefor k, v in d.items():

🐍 Try It Yourself — dict — Run It Directly

Run the concepts above as actual code. The fastest way to learn is to change the values and see firsthand how the behavior changes.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try Asking AI Like This

Knowing the concepts from this lesson lets you give AI specific instructions. Instead of a vague 'fix this', you make vocabulary-backed requests — that is where token savings begin.

  • 'Replace this list deduplication with a set'
  • 'Rewrite this dict merge using dict | dict (Python 3.9+)'

Why Does This Reduce Tokens?

Without understanding the concepts, you have to ask 'What does that mean?' after receiving an AI response. Those follow-up questions consume tokens. Master the concept once and the conversation ends in a single round.

dict — The Standard for Key-Value Storage - Python