Search⌘ K
AI Features

Dictionary: Use Cases

Understand how to use Python dictionaries to store object instances and attributes effectively. Learn different representation techniques including TypedDict, NamedTuple, and dataclasses. This lesson helps you decide the best approach for your design based on flexibility, efficiency, and testing needs.

Dictionaries are extremely versatile and have numerous uses. Here are two major examples:

Dict values: object’s instances

We can have dictionaries where all the values are different instances of objects with the same type. For example, our stock dictionary would have a type hint of dict[str, tuple[float, float, float]]. The string key maps to a three-tuple of values. We use the stock symbol as an index to price details. If we had a more complex Stock class, we might have a dictionary with dict[str, Stock] as the type hint for an index into these objects.

Dict values: object’s attributes

The second design is to have each key represent some aspect or attribute of a single object; the values often have distinct ...