Python course menu
Python Dictionaries: Keys, Values, Methods and Real Examples
Learn Python dictionaries step by step: create and access key-value pairs, get() with defaults, add, update and delete items, loop with items(), count things, nest dictionaries, merge them, and sort by value.
On this page
A dictionary (dict) stores data as key-value pairs. Instead of finding things by position like a list, you look them up by a meaningful key: a student's details by name, a product's price by its code. Dictionaries are one of the most used tools in all of Python.
Creating a dictionary#
Write key: value pairs inside curly braces:
student = {"name": "Asha", "age": 21, "city": "Pune"}
print(student["name"], student["age"])
print(len(student))Asha 21
3Keys are usually strings, but any immutable value (numbers, tuples) works. Values can be anything, including lists and other dictionaries. Dictionaries remember the order in which keys were added.
Reading values safely#
Square brackets fail if the key does not exist:
student = {"name": "Asha", "age": 21}
print(student["email"])KeyError: 'email'get() returns None, or a default you choose, instead:
print(student.get("email"))
print(student.get("email", "not provided"))None
not providedUse d[key] when the key must exist, and d.get(key, default) when it might not.
Adding, changing and removing#
Assigning to a key adds it, or replaces its value if it already exists:
student = {"name": "Asha", "age": 21}
student["age"] = 22
student["email"] = "asha@x.com"
print(student){'name': 'Asha', 'age': 22, 'email': 'asha@x.com'}removed = student.pop("email") # remove and return the value
del student["age"] # remove without returning
print(removed, student)asha@x.com {'name': 'Asha'}Checking for a key#
in checks keys, not values:
prices = {"tea": 20, "coffee": 35}
print("tea" in prices, 20 in prices, 20 in prices.values())True False TrueLooping over a dictionary#
prices = {"tea": 20, "coffee": 35, "juice": 50}
for item in prices: # keys
print(item)
for item, price in prices.items(): # key and value
print(item, price)
print(list(prices.keys()), list(prices.values()))tea
coffee
juice
tea 20
coffee 35
juice 50
['tea', 'coffee', 'juice'] [20, 35, 50]Counting with a dictionary#
A classic pattern: count how often each word appears.
sentence = "the cat and the hat and the bat"
counts = {}
for word in sentence.split():
counts[word] = counts.get(word, 0) + 1
print(counts){'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}counts.get(word, 0) returns the current count, or 0 the first time a word is seen. The standard library's Counter does this for you:
from collections import Counter
print(Counter("the cat and the hat and the bat".split()).most_common(2))[('the', 3), ('and', 2)]Nested dictionaries#
Values can be dictionaries or lists, which is how real data (and JSON) is usually shaped:
users = {
"asha": {"age": 21, "skills": ["python", "sql"]},
"ravi": {"age": 25, "skills": ["java"]},
}
print(users["asha"]["skills"][1])
users["ravi"]["skills"].append("python")
print(users["ravi"])sql
{'age': 25, 'skills': ['java', 'python']}Read nested access left to right: the "asha" entry, then its "skills" list, then item 1.
Merging dictionaries#
defaults = {"theme": "light", "font": 14}
user = {"font": 16}
settings = defaults | user # new dict; right side wins (Python 3.9+)
print(settings)
defaults.update({"theme": "dark"}) # changes defaults in place
print(defaults){'theme': 'light', 'font': 16}
{'theme': 'dark', 'font': 14}Building and sorting dictionaries#
A dictionary comprehension builds a dictionary in one line:
squares = {n: n * n for n in range(1, 5)}
print(squares){1: 1, 2: 4, 3: 9, 4: 16}To sort by value, sort the items():
prices = {"tea": 20, "coffee": 35, "juice": 50}
by_price = sorted(prices.items(), key=lambda kv: kv[1], reverse=True)
print(by_price)[('juice', 50), ('coffee', 35), ('tea', 20)]Common mistakes#
Practice#
Practice exercise
Given a list of orders as (customer, amount) tuples, compute each customer's total spend, then print the top customer and their total:
orders = [("Asha", 250), ("Ravi", 560), ("Asha", 120), ("Meera", 90), ("Ravi", 40)]Show hint
Use totals[name] = totals.get(name, 0) + amount. Then max(totals, key=totals.get) finds the key with the largest value.
Show solution
orders = [("Asha", 250), ("Ravi", 560), ("Asha", 120), ("Meera", 90), ("Ravi", 40)]
totals = {}
for name, amount in orders:
totals[name] = totals.get(name, 0) + amount
print(totals)
top = max(totals, key=totals.get)
print(top, totals[top]){'Asha': 370, 'Ravi': 600, 'Meera': 90}
Ravi 600This "group and total" pattern is the Python version of SQL's GROUP BY with SUM.
Key takeaway#
Finished this lesson?