Learn / Programming / Python / Dictionaries and Sets

Python · Lesson 7 of 15

Dictionaries and Sets

Key-value maps and unordered unique collections.

  • Beginner
  • 14 min read
  • 3 objectives

Before this lessonLesson 6: Lists and Tuples

What you will learn

  • Read and write dict keys
  • Iterate .items()
  • Use sets for uniqueness

A dictionary stores data as key-value pairs. Instead of asking "what is at position 2?" you ask "what is the value for the key "email"?". Lookups are very fast, on average constant time no matter how large the dictionary grows. Keys must be immutable (strings, numbers, tuples); values can be anything.

Look things up by name, not position

A list finds items by position: "give me item 3." But often you know a name, not a position: "what is Ada's email?" A dictionary works like a real dictionary or a phone contact list: you look up a key and get its value. It is one of the most useful tools in the language because so much real data is "a set of named fields": a user, a product, a settings file.

Creating and reading

user = {"id": 1, "email": "dev@example.com"}
user["role"] = "admin"      # add or update

print(user["email"])
print(user.get("phone", "n/a"))  # safe lookup with a default
print("role" in user)
Output
dev@example.com
n/a
True

Indexing a missing key with user["phone"] raises KeyError. Use .get(key, default) when the key may not exist. Remove entries with del user["role"] or user.pop("role").

Iterating

for key, val in user.items():
    print(key, "=", val)

print(list(user.keys()))
print(list(user.values()))
Output
id = 1
email = dev@example.com
role = admin
['id', 'email', 'role']
[1, 'dev@example.com', 'admin']

A classic pattern: counting

Dictionaries are the natural tool for counting things. counts.get(word, 0) + 1 reads the current count, treating a missing word as zero.

text = "the cat and the hat"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)
Output
{'the': 2, 'cat': 1, 'and': 1, 'hat': 1}

Sets

A set is an unordered collection of unique values. Adding a duplicate does nothing, which makes sets ideal for removing repeats and for fast membership checks. They also support math operations: union |, intersection & and difference -.

tags = {"python", "api", "python"}
print(tags)
print({1, 2, 3} & {2, 3, 4})
print(len(set([1, 1, 2, 2, 3])))
Output
{'python', 'api'}
{2, 3}
3

Reading, adding and safely looking up

user = {"name": "Ada", "role": "admin"}

print(user["name"])
user["email"] = "ada@example.com"   # add a new key
user["role"] = "owner"              # change a value

print(user.get("phone"))            # missing key -> None, no crash
print(user.get("phone", "n/a"))     # or supply a default
print("email" in user)
Output
Ada
None
n/a
True

Looping over a dictionary

prices = {"tea": 2.5, "coffee": 3.0, "juice": 4.25}

for item, price in prices.items():
    print(f"{item:<8} ${price:.2f}")

print(list(prices.keys()))
print(sum(prices.values()))
Output
tea      $2.50
coffee   $3.00
juice    $4.25
['tea', 'coffee', 'juice']
9.75

Worked example: counting words

Counting how often things appear is the classic dictionary job. The key is the thing being counted; the value is the running total.

text = "the cat and the hat and the bat"
counts = {}

for word in text.split():
    counts[word] = counts.get(word, 0) + 1

print(counts)
Output
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}

Nested data

Values can be lists or other dictionaries, which is how real data such as API responses is shaped. Read it one level at a time.

order = {
    "id": 1001,
    "customer": {"name": "Ada", "city": "London"},
    "items": [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}],
}

print(order["customer"]["city"])
print(order["items"][0]["qty"])
print(sum(i["qty"] for i in order["items"]))
Output
London
2
3

Sets: unique items and fast membership

a = {"python", "sql", "git"}
b = {"git", "docker", "sql"}

print(sorted(a & b))   # in both
print(sorted(a | b))   # in either
print(sorted(a - b))   # only in a
print(len({1, 1, 2, 2, 3}))
Output
['git', 'sql']
['docker', 'git', 'python', 'sql']
['python']
3

Each result is wrapped in sorted() for a reason: a set has no order, so printing one directly shows its items in an arbitrary arrangement that can differ between runs. Sort it whenever you need predictable output.

Key takeaways

  • A dictionary maps unique keys to values; use it when data has names.
  • Read with d[key] or the safe d.get(key, default).
  • Loop with .items(); counting is the classic pattern.
  • Sets store unique items and support union, intersection and difference.
# Write your solution here
Up next · Lesson 8Comprehensions and IterationBuild lists, dicts and sets in one line, and loop smarter with enumerate, zip and sorted.