Dictionaries

Part of the free LogicWiz Python course, Module 6: Dictionaries and sets. The examples and practice run in the app.

To find the price of Maggi, Canteen Counter scans the whole menu list, item by item. A dictionary jumps straight to it by name, like looking up a word in a real dictionary.

You'll learn to

  • Store key → value pairs and look a value up by its key
  • Use `get` with a default so a missing key does not crash
  • Loop with `keys`, `values` and `items`; change a dict with `update`, `del` and `pop`
  • Count how often things appear in one pass

Learn

Key → value

A dictionary (dict) stores pairs: menu = {"Chai": 10, "Samosa": 15}.

  • The part before : is the key ("Chai"), the part after is the value (10).
  • Look up by key: menu["Chai"] is 10. There are no positions like menu[0].
  • Keys are unique. Assigning to an existing key replaces its value; a new key adds a pair.
  • Since Python 3.7, a dict remembers the order you added the keys.

Look up, add, change

menu = {"Chai": 10, "Samosa": 15}
print(menu["Samosa"])
menu["Maggi"] = 30
menu["Chai"] = 12
print(menu)
print(len(menu), "Chai" in menu)

Line 3 adds a new pair. Line 4 does not add a second "Chai"; it replaces the value.

A missing key crashes

menu = {"Chai": 10, "Samosa": 15}
print(menu["Vada Pav"])

KeyError: 'Vada Pav'. Square brackets demand that the key exists.

get() with a default

menu = {"Chai": 10, "Samosa": 15}
print(menu.get("Samosa"))
print(menu.get("Vada Pav"))
print(menu.get("Vada Pav", 0))

get(key) returns None for a missing key instead of crashing; get(key, default) returns your default.

Looping and changing

menu = {"Chai": 10, "Samosa": 15, "Maggi": 30}
for item in menu:
    print(item, end=" ")
print()
print(list(menu.values()))
for item, price in menu.items():
    print(f"{item}: Rs {price}")

menu.update({"Poha": 20, "Chai": 12})
del menu["Maggi"]
print(menu)
print(menu.pop("Poha"), menu)

Looping over a dict gives its keys. .items() gives (key, value) tuples, which you unpack. update adds or replaces many pairs; del and pop remove one (and pop gives the value back).

The counting pattern

Remember counting items in Lesson 5.3 with a seen list and a loop inside a loop? A dict does it in one pass:

counts[item] = counts.get(item, 0) + 1

Read it as: "take the count so far (0 if this is the first time), add one, store it back." This single line answers half the "frequency" questions you will ever meet: letters in a word, words in a sentence, items sold today.

Counting today's orders

orders = ["chai", "samosa", "chai", "maggi", "chai"]
counts = {}
for item in orders:
    counts[item] = counts.get(item, 0) + 1
print(counts)
print(counts["chai"])

in on a dict checks keys, not values: with menu = {"Chai": 10}, "Chai" in menu is True but 10 in menu is False. Use 10 in menu.values() for values. And counts[item] += 1 crashes the first time an item appears, because the key isn't there yet.

CBSE asks: "Write a program to count the frequency of each character / word in a string using a dictionary", and predict-the-output on get, keys, values, items, update and pop. Know the difference: d[k] raises KeyError for a missing key, d.get(k) returns None.

In one line

d[k] crashes on a missing key, d.get(k, default) does not; in checks keys; count with d[x] = d.get(x, 0) + 1.