Python for Artificial Intelligence Intermediate 12 minutes

Dictionaries and Sets

Storing data as key-value pairs, and sets for unique elements.

Your progress in the track0%

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    # difference

Looking up an element in a set is usually faster than searching a large list, because a set relies on hashing.

When to use what?

NeedThe architecture
A mutable ordered sequencelist
Fixed ordered valuestuple
Lookup by keydict
Unique elements and set operationsset

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

  1. How do you read the value of a key that may not exist without an error?

    With d.get(key, default).

  2. 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

  1. Data Structures: Dictionaries — Python documentation
  2. Data Structures: Sets — Python documentation

Complete the lesson