Dictionary: Use Cases
Learn about the versatility of Python dictionaries, from mapping object instances to representing object attributes.
We'll cover the following
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 types. We may, for example, represent a stock with {'name': 'GOOG', 'current': 1245.21, 'range': (1252.64, 1245.18)}
. This case clearly overlaps with named tuples, data classes, and objects in general. Indeed, a special type hint for this kind of dictionary, called a TypedDict
, looks like a NamedTuple
type hint.
Get hands-on with 1400+ tech skills courses.