basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    Chapter 9PythonData

    Dicts and sets: lookup by key and counting without duplicates

    A dict maps a key to a value and finds it in one step, without scanning. A set stores unique values and checks membership right away. Count requests by IP address, group paths by status code and compare service lists.

    New hereDictionariesSetsGrouping: setdefault

    What you’ll get

    A list of IP addresses from a web server log. Count how many unique addresses showed up and how many requests each one made:

    # log_stats.py
    hits = [
        "203.0.113.10",
        "198.51.100.7",
        "203.0.113.10",
        "203.0.113.24",
        "203.0.113.10",
        "198.51.100.7",
    ]
    
    counts = {}
    for ip in hits:
        counts[ip] = counts.get(ip, 0) + 1
    
    print("Unique IPs:", len(counts))
    for ip, n in counts.items():
        print(f"{ip:<15} {n}")
    python log_stats.py
    # Unique IPs: 3
    # 203.0.113.10    3
    # 198.51.100.7    2
    # 203.0.113.24    1

    counts is a dict: each key is an address string and each value is a counter. counts.get(ip, 0) returns the current count or 0 if the address isn’t in the dict yet. counts.items() yields (key, value) pairs, which the loop unpacks into ip and n, just like tuples in Lists and tuples.

    What will it print?
    ports = {"ssh": 22, "http": 80}
    print(ports.get("https", 443))
    print("https" in ports)
    What will it print?
    Answer:
    443
    False

    get("https", 443) returns the fallback value without inserting the key into the dict. So "https" in ports stays False.

    How it works: a hash table

    In a list, x in items scans from start to finish: the longer the list, the slower the lookup. A dict (dict) and a set (set) are hash tables: Python computes a number — a hash — from the key and jumps straight to the matching slot.

    "ssh"   ──► hash("ssh")   ──► slot  ──► 22
    "http"  ──► hash("http")  ──► slot  ──► 80
    "https" ──► hash("https") ──► slot  ──► 443

    Checking key in ports and reading ports["ssh"] both take one step whether the dict has ten keys or a hundred thousand. The trade-off is a rule on keys: a key must be immutable, otherwise its hash could change after insertion. Strings, numbers and tuples work; a list can’t be a key — Python stops with a TypeError.

    A dict preserves the order in which keys were added. A set has no order: printing it outputs items in an arbitrary sequence.

    Read, change and loop over a dict

    Write a dict in curly braces as key: value pairs.

    Task Code Result
    read a value ports["ssh"] 22; missing key raises KeyError
    read with a fallback ports.get("ftp", 21) 21, dict stays unchanged
    add or replace ports["https"] = 443 inserts a new key or overwrites an existing one
    pop and remove p = ports.pop("http") returns 80 and removes the key; with fallback — pop("ftp", None)
    check for a key "ssh" in ports True (checks keys, not values)
    loop over keys for name in ports: "ssh", "http", "https"
    loop over pairs for name, p in ports.items(): key and value together
    loop over values for p in ports.values(): 22, 80, 443

    for x in ports: always iterates over keys. Use ports.values() for values alone and ports.items() for pairs. The same dict pattern powers Sort Downloads, where each file extension maps to a target folder.

    Grouping with setdefault

    When several values belong under one key, make the dict’s value a list. Here we group log paths by HTTP status code:

    events = [
        (200, "/"),
        (404, "/wp-login.php"),
        (200, "/en/python/"),
        (404, "/.env"),
    ]
    
    by_code = {}
    for code, path in events:
        by_code.setdefault(code, []).append(path)
    
    print(by_code)
    # {200: ['/', '/en/python/'], 404: ['/wp-login.php', '/.env']}

    setdefault(code, []) checks the key: if code is already there, it returns its list; if not, it inserts an empty list [] and returns it. Then .append(path) adds the item without a separate if. Duplicates uses the same pattern to group files by size and hash.

    Sets: unique items and set operations

    A set (set) stores keys alone, with no values and no duplicates. Build one from a list with duplicates using set(hits) — only the three unique addresses remain. Create an empty set with set(), because empty braces {} mean an empty dict in Python.

    Sets shine when comparing two collections. Compare which services should run on a server against what is currently running:

    wanted = {"traefik", "crowdsec", "beszel"}
    running = {"traefik", "beszel", "umami"}
    
    print(wanted - running)   # {'crowdsec'} — not running
    print(running - wanted)   # {'umami'} — unexpected
    print(wanted & running)   # {'beszel', 'traefik'} — in both
    print(wanted | running)   # all combined without duplicates

    Add an item with wanted.add("gatus") and remove one with wanted.discard("gatus"): unlike remove, discard won’t raise KeyError if the item isn’t there.

    Take it further

    Count how often each status code appears in [200, 404, 200, 500, 200, 404]

    Use the same counts.get(code, 0) + 1 pattern as for IP addresses.

    codes = [200, 404, 200, 500, 200, 404]
    counts = {}
    for code in codes:
        counts[code] = counts.get(code, 0) + 1
    print(counts)
    # {200: 3, 404: 2, 500: 1}
    Find unknown ports in [22, 80, 443, 8080] given known ports {"ssh": 22, "http": 80, "https": 443}

    Build a set of known ports with set(ports.values()) and subtract it from set(check).

    ports = {"ssh": 22, "http": 80, "https": 443}
    check = [22, 80, 443, 8080]
    unknown = set(check) - set(ports.values())
    print(unknown)
    # {8080}
    Group filenames ["report.pdf", "photo.jpg", "scan.pdf", "notes.txt", "avatar.jpg"] by extension

    Get the extension with name.split(".")[-1], and group with by_ext.setdefault(ext, []).append(name).

    names = ["report.pdf", "photo.jpg", "scan.pdf", "notes.txt", "avatar.jpg"]
    by_ext = {}
    for name in names:
        ext = name.split(".")[-1]
        by_ext.setdefault(ext, []).append(name)
    print(by_ext)
    # {'pdf': ['report.pdf', 'scan.pdf'], 'jpg': ['photo.jpg', 'avatar.jpg'], 'txt': ['notes.txt']}

    If it doesn’t work

    KeyError: '404'

    Cause
    Looked up a key that isn’t in the dict: counts["404"].
    Fix
    Read with counts.get("404", 0) or check first: if key in counts:.

    TypeError: cannot use 'list' as a dict key (unhashable type: 'list')

    Cause
    Used a list as a dict key or set element: {[1, 2]: "a"}. A list can mutate, so Python can’t compute a stable hash for it.
    Fix
    Use an immutable type: a string, a number or a tuple (1, 2).

    TypeError: 'dict' object is not callable

    Cause
    Used parentheses instead of square brackets — ports("ssh") — or named a variable dict = {}, shadowing the built-in dict().
    Fix
    Look up keys with square brackets: ports["ssh"]; give variables descriptive names like ports, counts or groups.

    AttributeError: 'dict' object has no attribute 'add'

    Cause
    Empty braces {} create an empty dict, not a set.
    Fix
    Create an empty set with set().

    RuntimeError: dictionary changed size during iteration

    Cause
    Added or deleted keys in the same dict while looping with for k in counts:.
    Fix
    Loop over a copy of the keys — for k in list(counts): — or build a new dict.