typestar

Dictionary views in Python

keys, values and items are live views, not copies.

tours = {"basics": 60, "pythonic": 53}
keys = tours.keys()

tours["domains"] = 40
print(sorted(keys))
print(keys & {"basics", "missing"})

print(sorted(tours.items())[0])
print(max(tours, key=tours.get))
try:
    for key in tours:
        tours["extra"] = 1
except RuntimeError as exc:
    print("mutation during iteration:", exc)

How it works

  1. A view reflects later changes to the dict.
  2. Key views support set operations.
  3. Iterating a view while mutating the dict raises.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
314
Tokens
106
Three-star pace
95 tpm

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

Type this snippet

Step 2 of 3 in Sets & mappings, step 57 of 72 in Language basics.

← Previous Next →