Skip to content

Beginner · Lists, tuples, dictionaries and sets · topic 16 of 50 · 25 min

Dictionaries: look things up by name

Explanation

A dictionary (dict) stores key-value pairs, like {"chai": 15, "samosa": 20}. You look up a value by its key instead of by a position number. get() gives a default when a key is missing, and items() lets you loop over keys and values together.

Look things up by name, not by number

In a list you find an item by its position. Often you want to find a value by a name instead: the price of chai, or the marks of Ravi. A dictionary (dict for short) stores key-value pairs. A key is the name you look up, and the value is what you get back. You write a dict with curly braces { }, with a colon between each key and its value.

python
menu = {"chai": 15, "samosa": 20, "vada pav": 25}
print(menu["samosa"])
print(len(menu))
Shows 20, then 3 because the menu has three pairs.
Think of it like this: A dict is like the contacts on your phone. You do not remember that Mummy is contact number 37. You search for the name "Mummy" (the key) and get her number (the value). Each name appears only once in your contacts.

Adding, updating and removing

python
menu = {"chai": 15, "samosa": 20}
menu["lassi"] = 40
menu["chai"] = 18
del menu["samosa"]
print(menu)
A new key adds a pair. An old key gets its value replaced. del removes a pair. Shows {'chai': 18, 'lassi': 40}.

Keys must be unique: one key holds only one value. Keys are usually strings or numbers. A key must be a value that cannot change, so a tuple can be a key but a list cannot. Values can be anything, even lists or other dicts.

Missing keys: KeyError and get()

output
menu = {"chai": 15}
print(menu["coffee"])
Gives KeyError: 'coffee' because that key does not exist.
python
menu = {"chai": 15}
print(menu.get("coffee"))
print(menu.get("coffee", 0))
print("chai" in menu)
get gives None, or the default you choose, instead of crashing. in checks the keys, so the last line shows True.
Careful: menu["coffee"] crashes with KeyError when the key is missing. When you are not sure a key exists, use menu.get("coffee", 0), or check with if "coffee" in menu first. Also remember: in checks the keys, not the values.

Looping over a dict

python
stock = {"rice": 8, "dal": 2, "oil": 5}
for item in stock:
    print(item)
print(sum(stock.values()))
for item, qty in stock.items():
    print(item, "->", qty)
A plain loop gives the keys. values() gives the values (here they add up to 15). items() gives (key, value) pairs that you can unpack.

Counting with a dict

python
votes = ["tea", "coffee", "tea", "lassi", "tea"]
counts = {}
for drink in votes:
    counts[drink] = counts.get(drink, 0) + 1
print(counts)
get(drink, 0) starts each new drink at 0. Shows {'tea': 3, 'coffee': 1, 'lassi': 1}.

Nested dicts: a shop's stock list

python
stock = {
    "rice": {"qty": 10, "price": 50},
    "dal": {"qty": 4, "price": 120},
}
print(stock["dal"]["price"])
stock["rice"]["qty"] -= 2
print(stock["rice"])
stock["dal"] is itself a dict, so a second ["price"] reaches inside it. Shows 120, then {'qty': 8, 'price': 50}.
Tip: A dict remembers the order in which you added the keys, so loops follow that order. Still, think of a dict as a lookup table, not a numbered list: there is no menu[0].

Watch the lesson

Dictionaries: look things up by name · 1/7

Dictionaries

In this lesson you will learn dictionaries, which let you look up a value by its name.

Prefer a video by a teacher? Find free videos on “python dictionary tutorial for beginners get items” on YouTube ↗

In real life: A kirana shop's stock and bill

Ramesh keeps his prices in a dict. When a customer buys some items, the program looks up each price by name, adds up the bill and reduces the stock. If an item is not in the price list, get() returns 0 instead of crashing the program in the middle of a sale.

python
prices = {"rice": 50, "dal": 120, "oil": 160}
stock = {"rice": 10, "dal": 4, "oil": 6}
order = {"rice": 2, "oil": 1}

bill = 0
for item, qty in order.items():
    bill += prices.get(item, 0) * qty
    stock[item] -= qty
print("Bill: Rs", bill)
print("Stock left:", stock)
Bill: Rs 260, and the stock of rice and oil goes down.

Practice (0/3 done)

Task 1 · Code · Python

Write a function price_of(menu, item) that returns the price of item from the dict menu, or 0 if the item is not on the menu.

Task 2 · Code · Python

Write a function count_words(words) that takes a list of words and returns a dict saying how many times each word appears. Example: count_words(["chai", "coffee", "chai"]) returns {"chai": 2, "coffee": 1}.

Task 3 · Code · Python

A shop's stock is a nested dict: each item maps to a dict with "qty" and "price". Write a function stock_value(stock) that returns the total value of all stock (qty times price, added up for every item).

Quick quiz

Question 1

1.d = {"a": 1, "b": 2}. What does d["b"] give?

Question 2

2.d = {"a": 1}. What does d.get("z", 0) give?

Question 3

3.d = {"x": 5}. What does d["y"] do?

Question 4

4.What does for k, v in d.items(): give you in each step?

Question 5

5.After d = {"chai": 15} and d["chai"] = 18, what is d?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: Tuples: fixed groups of values