Dictionaries
Learn about Python dictionaries’ efficient key-value data structures and learn to create, access, and manipulate them.
We'll cover the following
Overview
Dictionaries are incredibly useful containers that allow us to map objects directly to other objects. Dictionaries are extremely efficient at looking up a value, given a specific key object that maps to that value. The secret of the speed is using a hash of the key to locating the value. Every immutable Python object has a numeric hash code; a relatively simple table is used to map the numeric hashes directly to values. This trick means a dictionary never searches the entire collection for a key; the key is transformed into a hash, which locates the associated value (almost) immediately.
Creation
Dictionaries can be created either using the dict()
constructor or the {}
syntax shortcut. In practice, the latter format is almost always used. We can prepopulate a dictionary by separating the keys from the values using a colon and separating the key-value pairs using a comma.
We can also create dictionaries using keyword parameters. We can use dict(current = 1235.20, high = 1242.54, low = 1231.06)
to create the value {'current': 1235.2, 'high': 1242.54, 'low': 1231.06}
. This dict()
syntax overlaps with other constructors like dataclasses and named tuples.
Code example
For example, in our stock application, we would most often want to look up prices by the stock symbol. We can create a dictionary that uses stock symbols as keys and tuples (we can also use named tuples or dataclasses as values, of course)
of current
, high
, and low
as values, like this:
Get hands-on with 1400+ tech skills courses.