Beginner · Lists, tuples, dictionaries and sets · topic 16 of 50 · 25 min
Dictionaries: look things up by name
Explanation
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.
menu = {"chai": 15, "samosa": 20, "vada pav": 25}
print(menu["samosa"])
print(len(menu))Adding, updating and removing
menu = {"chai": 15, "samosa": 20}
menu["lassi"] = 40
menu["chai"] = 18
del menu["samosa"]
print(menu)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()
menu = {"chai": 15}
print(menu["coffee"])menu = {"chai": 15}
print(menu.get("coffee"))
print(menu.get("coffee", 0))
print("chai" in menu)Looping over a dict
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)Counting with a dict
votes = ["tea", "coffee", "tea", "lassi", "tea"]
counts = {}
for drink in votes:
counts[drink] = counts.get(drink, 0) + 1
print(counts)Nested dicts: a shop's stock list
stock = {
"rice": {"qty": 10, "price": 50},
"dal": {"qty": 4, "price": 120},
}
print(stock["dal"]["price"])
stock["rice"]["qty"] -= 2
print(stock["rice"])Watch the lesson
Dictionaries: look things up by name · 1/7
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.
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)Practice (0/3 done)
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.
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}.
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
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.