Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 29 of 70

Python dictionaries: storing data as key-value pairs

Learn Python dictionaries to store data by name. Create them, read and change values, handle missing keys safely, delete entries and check membership.

14 minCollectionsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonCreate a dictionary, read, add, change and delete entries by key, and handle a missing key without crashing.

After this lesson you can store information under meaningful names instead of positions, and look it up, change it and remove it. A dictionary (written dict in Python) is the natural way to hold a record such as one student or one product.

Keys and values

A list finds things by position. A dictionary finds things by a key that you choose. Each key is paired with a value:

python
student = {"name": "Asha", "age": 21, "course": "Python"}
print(student)
print(student["name"])
print(student["age"])
print(len(student))
print(type(student))
result
{'name': 'Asha', 'age': 21, 'course': 'Python'}
Asha
21
3
<class 'dict'>

Read the line student["name"] as "the value stored under the key name". The keys here are strings, but they can be any hashable value, such as numbers or tuples. Values can be anything at all, including lists and other dictionaries.

An empty dictionary is {}. You can also build one with dict():

python
empty = {}
point = dict(x=3, y=7)
pairs = dict([("a", 1), ("b", 2)])
print(empty)
print(point)
print(pairs)
result
{}
{'x': 3, 'y': 7}
{'a': 1, 'b': 2}

Adding and changing entries

Assigning to a key does one of two things. If the key is new it adds an entry. If the key exists it replaces the value.

python
student["city"] = "Pune"
student["age"] = 22
print(student)
result
{'name': 'Asha', 'age': 22, 'course': 'Python', 'city': 'Pune'}

Keys are unique. If you write the same key twice in one dictionary, the last value wins:

python
prices = {"tea": 20, "coffee": 30, "tea": 25}
print(prices)
result
{'tea': 25, 'coffee': 30}

Since Python 3.7 a dictionary also remembers the order in which keys were first added, and printing or looping gives them back in that order. This is part of the language, so you can rely on it. Older versions made no such promise.

Reading safely

Reading a key that is not there raises a KeyError:

python
student["email"]
result
KeyError: 'email'

When a missing key is normal and not a bug, use get. It returns None by default, or the second argument if you give one:

python
print(student.get("email"))
print(student.get("email", "not given"))
print(student.get("name", "not given"))
result
None
not given
Asha

You can also test first with in. For dictionaries in looks at the keys:

python
print("name" in student)
print("Asha" in student)
print("Asha" in student.values())
result
True
False
True

The second line is False because "Asha" is a value, not a key. Asking student.values() is how you search values.

Removing entries

Use del for a known key, or pop to remove it and get the value back. pop also accepts a default so that a missing key is not an error:

python
del student["city"]
print(student)
removed = student.pop("course")
print(removed)
print(student.pop("course", "already gone"))
print(student)
result
{'name': 'Asha', 'age': 22, 'course': 'Python'}
Python
already gone
{'name': 'Asha', 'age': 22}

Counting with a dictionary

A classic use is counting how often things occur. Keep each item as a key and its count as the value:

python
basket = ["pen", "book", "pen", "ruler", "pen", "book"]
counts = {}
for item in basket:
    counts[item] = counts.get(item, 0) + 1
print(counts)
result
{'pen': 3, 'book': 2, 'ruler': 1}

For every item, counts.get(item, 0) gives the count so far, or 0 for a new item, and we store it back plus one. Reading counts[item] directly would raise a KeyError on the first sight of each item, which is exactly why get with a default is so handy here.

What can be a key

Keys must be hashable, in practice immutable: strings, numbers, tuples of those, and so on. A list is not allowed, because it could change after being stored.

python
bad = {[1, 2]: "list key"}
result
TypeError: unhashable type: 'list'

Tuples work, which is useful for things like grid positions:

python
board = {(0, 0): "X", (1, 1): "O"}
print(board[(1, 1)])
result
O

Common mistakes

  • Reading a missing key with square brackets. It raises KeyError. Use get or check with in when the key may not exist.
  • Checking in for a value. in tests keys. Use .values() to test values.
  • Repeating a key and expecting both entries. The later value silently replaces the earlier one.
  • Using a list as a key. Use a tuple, or rethink the structure.
  • Confusing {} with an empty set. {} is an empty dictionary; use set() for a set.

Exercise

Create a dictionary book with the keys "title", "author" and "pages" for any fictional book. Add a key "available" set to True, change "pages" to a new number, and print the title using get with a default of "unknown". Then print what get returns for a key "isbn" that does not exist.

Show one possible answer
python
book = {"title": "Learning Maps", "author": "R. Example", "pages": 180}
book["available"] = True
book["pages"] = 200
print(book.get("title", "unknown"))
print(book.get("isbn"))
print(book)
result
Learning Maps
None
{'title': 'Learning Maps', 'author': 'R. Example', 'pages': 200, 'available': True}

Previous: Sets. Next: Dictionary methods and loops.

Key points

  • A dictionary maps keys to values and is written with curly braces: {"name": "Asha", "age": 21}.
  • Read a value with d[key]. A missing key raises KeyError, while d.get(key) returns None or a default you supply.
  • Assigning to a key adds it if new or replaces the value if it exists. Keys must be unique and hashable.
  • From Python 3.7 a dictionary remembers the order in which keys were inserted. The in operator checks keys, not values.

Check yourself

1. What does {"a": 1, "a": 2} contain?
2. How do you read a value without risking a KeyError?
3. What does "apple" in prices check for a dictionary called prices?
4. Which of these cannot be a dictionary key?