Builder to Architect
Python

Dictionaries & Strings in Python

Master dictionaries (key-value pairs) — the most useful data structure for real-world data — and learn powerful string manipulation techniques.

Dictionaries — Data with Labels

Lists store items by position (index 0, 1, 2...). But real-world data has labels. A client isn't "item 3" — they have a name, a country, a deal value.

Dictionaries store data as key-value pairs:

client = {
    "name": "Lamaria Honey",
    "country": "France",
    "deal_value": 50000,
    "is_active": True
}

Access values by key (not by index):

print(client["name"])        # → "Lamaria Honey"
print(client["deal_value"])  # → 50000

If you've worked with JSON (in your web projects), you already know this structure. A Python dictionary IS essentially the same as a JSON object.

Dictionary Operations

client = {"name": "Lamaria Honey", "country": "France"}

# Add or update
client["deal_value"] = 50000
client["country"] = "Belgium"   # Updates existing key

# Check if key exists
if "email" in client:
    print(client["email"])
else:
    print("No email on file")

# Safe access with .get() (no error if key missing)
email = client.get("email", "N/A")  # → "N/A" (default value)

# Remove
del client["is_active"]

# Get all keys, values, or pairs
client.keys()    # → dict_keys(["name", "country", "deal_value"])
client.values()  # → dict_values(["Lamaria Honey", "Belgium", 50000])
client.items()   # → dict_items([("name", "Lamaria Honey"), ...])

Looping Through Dictionaries

client = {"name": "Lamaria Honey", "country": "France", "deal_value": 50000}

# Loop through keys
for key in client:
    print(f"{key}: {client[key]}")

# Loop through key-value pairs (more elegant)
for key, value in client.items():
    print(f"{key}: {value}")

Nested Dictionaries — Real Data

Real data is often nested:

portfolio = {
    "lamaria": {
        "name": "Lamaria Honey",
        "country": "France",
        "products": ["Wildflower Honey", "Mountain Honey"],
        "deal_value": 50000
    },
    "sadili": {
        "name": "Sadili LLC",
        "country": "Germany",
        "products": ["Canned Meat", "Pickled Vegetables"],
        "deal_value": 75000
    }
}

# Access nested data
print(portfolio["lamaria"]["products"][0])  # → "Wildflower Honey"

# Loop and calculate
total = sum(c["deal_value"] for c in portfolio.values())
print(f"Total portfolio: ${total}")  # → Total portfolio: $125000

This is the same pattern as the JSON data in your web projects. Understanding dictionaries deeply helps you work with APIs, databases, and configuration files.

String Methods

Strings in Python have many built-in methods:

text = "  Hello, World!  "

text.strip()         # → "Hello, World!" (remove whitespace)
text.lower()         # → "  hello, world!  "
text.upper()         # → "  HELLO, WORLD!  "
text.replace("World", "Lia")  # → "  Hello, Lia!  "
text.split(",")      # → ["  Hello", " World!  "]
text.startswith("  H")  # → True
text.endswith("!")   # → False (trailing spaces)
text.strip().endswith("!")  # → True

String Formatting

name = "Lia"
amount = 50000.5

# f-string (best way)
f"Deal: {name} for ${amount:,.2f}"   # → "Deal: Lia for $50,000.50"

# The :,.2f means: comma separator, 2 decimal places, float format
f"${amount:>10,.0f}"   # → "    50,001" (right-aligned, 10 chars wide)

Multiline Strings

email = f"""Dear {name},

Thank you for your order of ${amount:,.0f}.
We will process it within 3 business days.

Best regards,
GEC Business Growth Services"""

join() — The Opposite of split()

countries = ["France", "Belgium", "Turkey"]
result = ", ".join(countries)   # → "France, Belgium, Turkey"

# Useful for creating CSV-like output
header = "\t".join(["Name", "Country", "Value"])  # tab-separated

Combining Dictionaries and Strings

clients = [
    {"name": "Lamaria Honey", "country": "France", "value": 50000},
    {"name": "Sadili LLC", "country": "Germany", "value": 75000},
    {"name": "Pavilion Wines", "country": "Belgium", "value": 30000},
]

# Generate a report
print("Export Portfolio Report")
print("=" * 40)
for client in clients:
    print(f"{client['name']:20s} | {client['country']:10s} | ${client['value']:>10,}")
print("=" * 40)
total = sum(c["value"] for c in clients)
print(f"{'Total':20s} | {'':10s} | ${total:>10,}")

Output:

Export Portfolio Report
========================================
Lamaria Honey        | France     |    $50,000
Sadili LLC           | Germany    |    $75,000
Pavilion Wines       | Belgium    |    $30,000
========================================
Total                |            |   $155,000

What to Do This Week

  1. Read Chapters 5 and 6 of Automate the Boring Stuff
  2. Build a client database: Create a Python script with a list of dictionaries representing your export clients. Practice accessing, filtering, and formatting the data.
  3. Take the quiz below.

Quiz

Question 1/5Score: 0

How do you access a value in a dictionary?