Python

Cheat sheet · Level 10

Dictionaries

Every command and idea of this level on one page: what to type, what it does, and what you see.

Take the level exam
  1. 1Labels and values

    Dictionaries connect a key to a value.

    What to typeWhat it doesYou see
    print(prices["tea"])Look up tea·
    print(prices["cake"])Look up cake3 7
  2. 2Add and change

    Put new pairs in.

    What to typeWhat it doesYou see
    prices["juice"] = 4Add juice·
    prices["tea"] = 5Change tea{'tea': 5, 'cake': 7, 'juice': 4} False
  3. 3Visit every pair

    items().

    What to typeWhat it doesYou see
    for name, price in prices.items():Use itemstea: 3 cake: 7 juice: 4
  4. 4Only the values, or the keys

    values() and keys().

    What to typeWhat it doesYou see
    print(sum(prices.values()))Use values·
    print(len(prices.keys()))Use keys14 3
  5. 5Safe look-ups

    get() gives a default.

    What to typeWhat it doesYou see
    print(prices.get("milk", 0))Use get0 3
  6. 6Count with get

    Add one, even to a new count.

    What to typeWhat it doesYou see
    counts[f] = counts.get(f, 0) + 1Use get·
    for f in basket:Use a loop{'apple': 2, 'pear': 1}