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
- Assignment adds keys;
getreads with a safe default. - The
|operator merges two dicts into a new one. itemsiterates pairs;keyslists the keys.maxwithkey=scores.getfinds the top entry.
Keywords and builtins used here
forlistmaxprint
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.
Step 1 of 10 in Collections, step 23 of 72 in Language basics.