Dictionaries and Sets
Storing data as key-value pairs, and sets for unique elements.
Dictionaries
model = {"name": "ResNet", "layers": 50, "pretrained": True}
model["layers"] # 50
model["optimizer"] = "Adam" # add a key
model.get("dropout", 0.0) # a default value if it does not exist
"name" in model # True
del model["pretrained"]Going over a dictionary
for key, value in model.items():
print(key, "→", value)keys() andvalues() anditems() return views of the dictionary's contents.
Counting with a dictionary
words = "the cat and the dog".split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
# {'the': 2, 'cat': 1, 'and': 1, 'dog': 1}The standard library provides collections.Counter to do this directly.
Dictionary comprehensions
labels = ["cat", "dog", "bird"]
label_to_id = {lbl: i for i, lbl in enumerate(labels)}This pattern is common for converting class names to numbers before training a model.
Sets
a = {"python", "numpy", "pandas"}
b = {"pandas", "sklearn"}
a | b # union
a & b # intersection {'pandas'}
a - b # differenceLooking up an element in a set is usually faster than searching a large list, because a set relies on hashing.
When to use what?
| Need | The architecture |
|---|---|
| A mutable ordered sequence | list |
| Fixed ordered values | tuple |
| Lookup by key | dict |
| Unique elements and set operations | set |
Lesson terms
- Hashability
- An object having a fixed hash value that allows it to be used as a dictionary key or a set element.
- Dictionary
- A structure that maps unique keys to values and allows lookup by key in roughly constant average time.
- Set
- A structure containing unique elements with no guaranteed order, supporting mathematical set operations.
Abstract
A dict maps unique keys to values and allows fast access to them, and it has preserved insertion order since Python 3.7. A set contains unique, unordered elements and supports union, intersection and difference operations. Keys and set elements must be hashable.
Review questions
-
How do you read the value of a key that may not exist without an error?
With d.get(key, default).
-
How do you remove duplicates from a list?
By converting it to a set, noting that the order may not be preserved.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate