typestar

Dictionary operations in Python

The key-value workhorse: reading, writing, and merging dicts.

scores = {"ada": 95, "grace": 88}

scores["katherine"] = 92
ada = scores.get("ada", 0)
missing = scores.get("alan", 0)

defaults = {"theme": "dark", "sound": True}
settings = defaults | {"sound": False}

for name, score in scores.items():
    print(f"{name}: {score}")

names = list(scores.keys())
best = max(scores, key=scores.get)

How it works

  1. Assignment adds keys; get reads with a safe default.
  2. The | operator merges two dicts into a new one.
  3. items iterates pairs; keys lists the keys.
  4. max with key=scores.get finds the top entry.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
328
Tokens
121
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 81 seconds.

Type this snippet

Step 1 of 10 in Collections, step 23 of 72 in Language basics.

← Previous Next →