Good design adds value faster than it adds cost.
Hey pips!
Today we look at one of the most important constructs in all of programming – the dictionary.
A physical dictionary matches words to definitions. In programming, a dictionary matches keys to values.
[!Note] Technically speaking, it’s called an associative array since it associates each key with a value, unlike a regular array or
list
which tracks items via a numerial index. You might also hear a dictionary called a hash, map or hashmap.
In Python, the dictionary class is dict
, and since it’s a core data type, it has its own special syntax:
addictive = {
"python": True,
"programming": True,
}
The keys of a dict
can be any immutable data type, but we most commonly use str
. The values can be any type, including another dict
!
d = {
"water": {"H": 2, "O": 1},
"glucose": {"C": 6, "H": 12, "O": 6},
}
We access values by indexing the dictionary with a key. Because of the way dict
works, this is a constant time operation, meaning its speed won’t be affected by the size of the dictionary.
>>> d["water"]
{'H': 2, 'O': 1}
>>> d["glucose"]["H"]
12
To add or update a key, just assign a value to it. If it doesn’t exist already, it’ll be created.
>>> d["sulphuric-acid"] = {
"H": 2,
"S": 1,
"O": 4,
}
Iterating over a dict
yields its keys in the order they were defined and/or inserted.
>>> elems = {
"C": 6,
"Si": 14,
}
>>> for key in elems:
print(f"{key} = {elems[key]}")
C = 6
Si = 14
You can also access the keys via the .keys()
method, and likewise .values()
for the values. Like enumerate()
, range()
and zip()
, these don’t exactly return a list, but rather a proxy to the dictionary.
>>> list(elems.keys())
["C", "Si"]
>>> list(elems.values())
[6, 14]
Before we used elems[key]
while iterating to access the corresponding value, but just like how enumerate()
provides us with the index of an iterable, the .items()
method of a dict
outputs (key, value)
pairs for us to iterate over:
>>> for key, val in elems.items():
print(f"{key} = {val}")
C = 6
Si = 14
We’ve now assembled our 4 fundamental types – int
, string
, list
, dict
– or more generally, numbers, text, arrays and dictionaries.
What’s special is that with these 4 types alone, we can represent anything. If addition, subtraction, multiplication and division are the essence of maths, then numbers, text, arrays and dictionaries are the essence of programming.
[!Tip] Booleans (
True
/False
) can be represented with numbers (1
/0
), and this is actually how Python represents them!
Any object, relationship or data structure can be defined in terms of these fundamental types. For instance, we could represent a pycobytes issue like so:
issue = {
"title": "The Mighty Dictionary",
"index": 18,
"date": {
"year": 2024,
"month": 12,
"day": 17,
},
"tags": ["dictionaries", "types"],
}
Why dictionaries are so powerful is because they essentially represent objects, the bread and butter of most programming we do. They allow you to map ‘properties’ to values, and group them into a single container.
Further Reading
The number, text, array and dictionary types are so fundamental that they’re the basis of JSON↗, probably one of the most used data interchange formats in software development.
Associative arrays can have different implementations which impacts their performance – Wikipedia↗