Chapter 6: Dictionaries

Dictionaries map keys to values. The workhorse for structured data.

Creating Dictionaries

Curly braces, key-value pairs:

server = {
    'hostname': 'web-01',
    'ip': '10.0.1.10',
    'port': 443,
    'active': True
}

Or from scratch:

server = {}
server['hostname'] = 'web-01'
server['ip'] = '10.0.1.10'

Accessing Values

server['hostname']  # 'web-01'
server['port']      # 443

KeyError

Accessing missing key raises error:

server['location']  # KeyError: 'location'

Use get() for safe access:

server.get('location')           # None (no error)
server.get('location', 'unknown') # 'unknown' (default)

Modifying Dictionaries

server = {'hostname': 'web-01', 'port': 80}

# Add or update
server['port'] = 443
server['ssl'] = True

# Remove
del server['ssl']

# Pop (remove and return)
port = server.pop('port')  # port = 443

Looping

Key-Value Pairs

server = {'hostname': 'web-01', 'ip': '10.0.1.10', 'port': 443}

for key, value in server.items():
    print(f"{key}: {value}")
hostname: web-01
ip: 10.0.1.10
port: 443

Keys Only

for key in server.keys():
    print(key)

# Or simply (keys is default)
for key in server:
    print(key)

Values Only

for value in server.values():
    print(value)

Sorted Keys

for key in sorted(server.keys()):
    print(f"{key}: {server[key]}")

Membership

'hostname' in server        # True (checks keys)
'web-01' in server.values() # True (checks values)

Nesting

List of Dictionaries

servers = [
    {'hostname': 'web-01', 'ip': '10.0.1.10'},
    {'hostname': 'web-02', 'ip': '10.0.1.11'},
    {'hostname': 'db-01', 'ip': '10.0.2.10'},
]

for server in servers:
    print(f"{server['hostname']}: {server['ip']}")

Dictionary of Lists

server = {
    'hostname': 'web-01',
    'ports': [80, 443, 8080],
    'users': ['admin', 'deploy']
}

for port in server['ports']:
    print(f"Open port: {port}")

Dictionary of Dictionaries

infrastructure = {
    'web-01': {
        'ip': '10.0.1.10',
        'services': ['nginx', 'node']
    },
    'db-01': {
        'ip': '10.0.2.10',
        'services': ['postgres']
    }
}

for hostname, config in infrastructure.items():
    print(f"\n{hostname}:")
    print(f"  IP: {config['ip']}")
    print(f"  Services: {', '.join(config['services'])}")

Dictionary Comprehensions

# Square numbers
squares = {n: n**2 for n in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# From two lists
hosts = ['web-01', 'db-01']
ips = ['10.0.1.10', '10.0.2.10']
inventory = {h: ip for h, ip in zip(hosts, ips)}
# {'web-01': '10.0.1.10', 'db-01': '10.0.2.10'}

Common Patterns

Counting

words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
# {'apple': 3, 'banana': 2, 'cherry': 1}

Grouping

servers = ['web-01', 'web-02', 'db-01', 'cache-01']
by_type = {}
for server in servers:
    server_type = server.split('-')[0]
    if server_type not in by_type:
        by_type[server_type] = []
    by_type[server_type].append(server)
# {'web': ['web-01', 'web-02'], 'db': ['db-01'], 'cache': ['cache-01']}

Default Values

config = {'debug': True}
port = config.get('port', 8080)  # 8080 if not set

Quick Reference

Operation Code

Create

d = {'key': 'value'}

Access

d['key'], d.get('key', default)

Set

d['key'] = value

Delete

del d['key'], d.pop('key')

Keys

d.keys(), 'key' in d

Values

d.values()

Items

d.items()

Length

len(d)

Comprehension

{k: v for k, v in items}

Exercises

6-1. Person

Create a dict with: first_name, last_name, age, city. Print each.

6-2. Favorite Numbers

Map 5 friends to their favorite numbers. Print each.

6-3. Glossary

Create a dict of 5 programming terms and definitions. Print formatted.

6-4. Servers

Create a list of 3 server dicts (hostname, ip, status). Loop and print.

6-5. Rivers

Map rivers to countries. Loop through: - All key-value pairs - Just river names - Just country names

6-6. Counting

Count occurrences in: ['a', 'b', 'a', 'c', 'b', 'a', 'd', 'c', 'a']

Summary

  • Dictionaries map keys to values: {'key': value}

  • Access with [] or .get() for safety

  • Loop with .items(), .keys(), .values()

  • Nest freely: lists in dicts, dicts in lists, dicts in dicts

  • Comprehensions: {k: v for k, v in items}

Next: User input and while loops.