Skip to content
Laviyx Learn

Try

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.

Beginner7 min readUpdated
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:

Python
student = {"name": "Asha", "age": 21, "city": "Pune"}
print(student["name"], student["age"])
print(len(student))
Output
Asha 21
3

Keys 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:

Python
student = {"name": "Asha", "age": 21}
print(student["email"])
Output
KeyError: 'email'

get() returns None, or a default you choose, instead:

Python
print(student.get("email"))
print(student.get("email", "not provided"))
Output
None
not provided

Use 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:

Python
student = {"name": "Asha", "age": 21}
student["age"] = 22
student["email"] = "asha@x.com"
print(student)
Output
{'name': 'Asha', 'age': 22, 'email': 'asha@x.com'}
Python
removed = student.pop("email")   # remove and return the value
del student["age"]               # remove without returning
print(removed, student)
Output
asha@x.com {'name': 'Asha'}

Checking for a key#

in checks keys, not values:

Python
prices = {"tea": 20, "coffee": 35}
print("tea" in prices, 20 in prices, 20 in prices.values())
Output
True False True

Looping over a dictionary#

Python
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()))
Output
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.

Python
sentence = "the cat and the hat and the bat"
counts = {}
for word in sentence.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)
Output
{'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:

Python
from collections import Counter
print(Counter("the cat and the hat and the bat".split()).most_common(2))
Output
[('the', 3), ('and', 2)]

Nested dictionaries#

Values can be dictionaries or lists, which is how real data (and JSON) is usually shaped:

Python
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"])
Output
sql
{'age': 25, 'skills': ['java', 'python']}

Read nested access left to right: the "asha" entry, then its "skills" list, then item 1.

Merging dictionaries#

Python
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)
Output
{'theme': 'light', 'font': 16}
{'theme': 'dark', 'font': 14}

Building and sorting dictionaries#

A dictionary comprehension builds a dictionary in one line:

Python
squares = {n: n * n for n in range(1, 5)}
print(squares)
Output
{1: 1, 2: 4, 3: 9, 4: 16}

To sort by value, sort the items():

Python
prices = {"tea": 20, "coffee": 35, "juice": 50}
by_price = sorted(prices.items(), key=lambda kv: kv[1], reverse=True)
print(by_price)
Output
[('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:

Python
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
Python
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])
Output
{'Asha': 370, 'Ravi': 600, 'Meera': 90}
Ravi 600

This "group and total" pattern is the Python version of SQL's GROUP BY with SUM.

Key takeaway#

Finished this lesson?