Dictionary Iteration and Comprehension
Objectives
By the end of this chapter, you should be able to:
- Iterate over a dictionary
- Create dictionaries using dictionary comprehension
- Use tuples and sets
💡 Why this matters: You’ll loop over and transform dictionaries as often as lists. Tuples and sets round out the collection types you’ll reach for, depending on whether you need something unchangeable or something with no duplicates.
Iterating Over a Dictionary
A for...in loop over a dictionary iterates over its keys by default:
d = dict(name="Erin", job="Instructor")
for k in d:
print(k)
# name
# job
To get both the key and the value, loop over .items():
d = dict(name="Erin", job="Instructor")
for key, value in d.items():
print(f"{key}:{value}")
# name:Erin
# job:Instructor
Dictionary Comprehension
You can pull values or keys out of a dictionary using a list comprehension:
d = {"a": 1, "c": 3, "e": 5}
[v for k, v in d.items()] # [1, 3, 5]
[k for k, v in d.items()] # ['a', 'c', 'e']
You can also go the other way: build a dictionary from another data type, using {key: value for ...} instead of [...]:
str1 = "ABC"
str2 = "123"
{str1[i]: str2[i] for i in range(len(str1))}
# {'A': '1', 'B': '2', 'C': '3'}
That takes each index i from 0 up to (but not including) the length of str1, using the character at that index in str1 as the key and the character at the same index in str2 as the value.
Dictionary comprehension also supports conditional values, not just conditional filtering:
num_list = [1, 2, 3, 4]
{num: ("even" if num % 2 == 0 else "odd") for num in num_list}
# {1: 'odd', 2: 'even', 3: 'odd', 4: 'even'}
Tuples
A tuple is another Python collection, but immutable: once created, you can’t reassign its elements. That immutability makes tuples faster to work with than lists, so if you have a fixed collection of values you’ll only ever read (not modify), reach for a tuple instead. You build one with parentheses instead of square brackets, and you read from it the same way you read from a list, with [index]:
x = (1, 2, 3)
x[0] # 1
3 in x # True
x[0] = "change me!" # TypeError: tuples don't support item assignment
Tuples support two main methods:
| Method | Does |
|---|---|
.count(x) |
Counts how many times x appears |
.index(x) |
Returns the index of the first match; raises ValueError if not found |
Tuples show up naturally when you pull a string apart. str.split(sep) breaks a string into a list of pieces at every occurrence of sep, and int() converts a numeric string into an actual integer you can do math with:
coords = "3,4"
parts = coords.split(",")
parts # ['3', '4']
x, y = int(parts[0]), int(parts[1])
(x, y) # (3, 4)
Sets
A set stores unique, unordered values: duplicates are automatically dropped, and there’s no indexing since there’s no order to index into. Sets are useful when you need to track membership (is this value in the collection?) without caring about order or duplicates:
s = {1, 2, 3, 4, 5, 5, 5} # {1, 2, 3, 4, 5} (duplicates collapse automatically)
4 in s # True
8 in s # False
You can also build a set from an existing list with the set() function. This is a common way to strip out duplicates or check how many unique values a list has:
nums = [1, 2, 2, 3, 3, 3]
unique_nums = set(nums)
unique_nums # {1, 2, 3}
len(nums) # 6
len(unique_nums) # 3, because the duplicates were dropped
Sets have no fixed order, so printing a set of strings can show its values in a different order than you typed them. That’s expected: don’t rely on the order of a set.
Common set methods:
| Method | Does |
|---|---|
.add(x) |
Adds x (no effect if it’s already present) |
.clear() |
Removes every element |
.copy() |
Returns a new, independent set |
.difference(other) |
Elements in this set but not in other |
.intersection(other) |
Elements in both sets |
.symmetric_difference(other) |
Elements in exactly one of the two sets |
.union(other) |
Elements in either set |
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set1.difference(set2) # {1}
set1.intersection(set2) # {2, 3}
set1.symmetric_difference(set2) # {1, 4}
set1.union(set2) # {1, 2, 3, 4}
Try It
- Loop over a dictionary’s
.items()and print each pair as a full sentence. - Write a dictionary comprehension that builds a dictionary from two same-length lists, matched up by index.
- Create two sets with some overlapping values and try
.union(),.intersection(), and.difference()on them. - Build a list with some repeated values, convert it to a set with
set(), and comparelen()of each to see how many duplicates were removed.
Recap
for key in dictionaryloops over keys by default;.items()gives you both key and value.- Dictionary comprehension (
{key: value for ...}) builds a dictionary in one line, from any iterable. - Tuples are immutable, ordered collections you read with
[index]; sets are unordered collections of unique values, built with{}orset(existing_list), with methods like.union()and.intersection().
Next lesson: put dictionaries and dictionary comprehension into practice with a set of exercises.