Skip to content

Module 8 · Python Data Structures — topic 17 of 22

Dictionaries

Dictionaries map unique keys to values for instant lookup. Learn how to create them, read values by key, what can be a key, insertion order, and why dictionaries are central to Python.

Beginner 12 min read·Lesson 120 of 306 in Python Programming

Learning objectives

  • Create dictionaries and look up values by key
  • Explain key uniqueness and hashability
  • Choose a dictionary for lookup-style problems

Definition

Dictionaries map unique keys to values for instant lookup. Learn how to create them, read values by key, what can be a key, insertion order, and why dictionaries are central to Python.

Introduction

A dictionary stores pairs: each key maps to a value, like a word and its meaning in a real dictionary. {"tea": 20, "coffee": 35} maps item names to prices, and prices["tea"] gives 20.

Why it matters

Looking things up by name or ID is one of the most common operations in software: a student by roll number, a price by product code, a setting by its name. Dictionaries make these lookups instant and the code self-explanatory.

Detailed explanation

Create a dictionary with braces and key: value pairs, with dict(name=value) keyword arguments, or with dict() from a list of pairs. {} is an empty dictionary.

d[key] returns the value for key and raises KeyError if the key doesn’t exist. d.get(key, default) returns a default instead.

Keys are unique: assigning to an existing key replaces its value.

Keys must be hashable (strings, numbers, tuples of immutable values). Values can be anything, including lists and other dictionaries.

Dictionaries remember the order in which keys were inserted (guaranteed since Python 3.7).

Lookups use hashing, so they are fast regardless of size, like set membership.

len(d) counts pairs, key in d checks keys, and iterating over d gives keys.

Syntax

Python
prices = {"tea": 20, "coffee": 35}
empty = {}
person = dict(name="Asha", age=21)
value = prices["tea"]
safe = prices.get("juice", 0)
  • Pairs are written key: value.
  • d[key] looks up a value.
  • get() supplies a default for missing keys.

Code examples

Creating and looking up

Python
prices = {"tea": 20, "coffee": 35, "juice": 50}
print(prices["coffee"])
print(prices.get("lassi", "not on menu"))
print(len(prices), "tea" in prices)
person = dict(name="Asha", age=21)
print(person)
Output
35
not on menu
3 True
{'name': 'Asha', 'age': 21}

KeyError and unique keys

Python
stock = {"pen": 10, "pen": 25}
print(stock)
try:
stock["ink"]
except KeyError as err:
print("KeyError:", err)
Output
{'pen': 25}
KeyError: 'ink'

More examples

A roll-number lookup

Python
students = {
101: {"name": "Asha", "city": "Pune"},
102: {"name": "Ben", "city": "Delhi"},
103: {"name": "Chen", "city": "Goa"},
}
for roll in [102, 105]:
record = students.get(roll)
if record is None:
print(roll, "not found")
else:
print(roll, record["name"], "from", record["city"])
pairs = [("Mon", 3), ("Tue", 5)]
classes = dict(pairs)
print(classes, list(classes))
Output
102 Ben from Delhi
105 not found
{'Mon': 3, 'Tue': 5} ['Mon', 'Tue']

Step-by-step explanation

  • Roll numbers are the keys; each value is a small dictionary describing the student.
  • get(roll) returns None for unknown roll numbers instead of raising KeyError.
  • Nested lookups such as record["name"] read fields from the inner dictionary.
  • dict(pairs) builds a dictionary from a list of (key, value) tuples; list() of a dict gives its keys in insertion order.

Expected output

Running “A roll-number lookup” prints exactly:

TextOutput
102 Ben from Delhi
105 not found
{'Mon': 3, 'Tue': 5} ['Mon', 'Tue']

Practical applications

  • JSON data from web APIs becomes Python dictionaries.
  • Caches store computed results keyed by their inputs.
  • Settings and configuration are stored as name–value dictionaries.

Best practices

  • Use meaningful, stable keys such as IDs.
  • Use get() when a key may be missing.
  • Keep values of one kind for the same dictionary.

Common mistakes

Using a missing key directly

Avoid

price = prices["lassi"]

Prefer

price = prices.get("lassi", 0)

A missing key raises KeyError; get() returns a default.

Expecting duplicate keys to keep both values

Avoid

{"pen": 10, "pen": 25} # expecting both

Prefer

{"pen": [10, 25]}

Keys are unique; the later value replaces the earlier one. Store a list if you need several values.

Key takeaways

  • Dictionaries map unique, hashable keys to values.
  • d[key] looks up a value; get() avoids KeyError.
  • Dictionaries keep insertion order and look up keys quickly.

Try it yourself

  1. 1
    Create a dictionary of five countries and their capitals and print the capital of a country the user types.
  2. 2
    Build a dictionary from two lists, names and marks, using zip().

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic