What are dictionaries in python?
Exploring the structured data concept
In prior articles, we've discussed some techniques for storing data in python; concepts like lists and simple variables. Today, I want to unpack another concept: dictionaries. What are they and how do they work? Don't worry - I'll keep this fairly brief 😄.
Dictionaries are a fundamental data structure in python and very useful. They work very similar to physical dictionary. Anyone remember those?
A printed dictionary groups information together. It allows the reader to lookup a word and see its definition. In a programming mindset, we can think of this a Key-Value pair. The key is used to help the reader locate the associated value. If it helps, you can also visualize this as a table:
Key | Value |
---|---|
Lightsaber | Super cool sword |
Coffee | Beverage providing energy |
The syntax for a dictionary in python looks like this: {Key: Value}
So continuing the example from earlier, a dictionary in python would look like this:
{"Lightsaber": "Super cool sword"}
That's just one entry though. You can add multiple entries by adding comma-separate pairs:
{
"Lightsaber": "Super cool sword",
"Coffee": "Beverage providing energy",
}
OK, so that's all well and good... but why is this useful? What makes python dictionaries helpful? Basically it boils down a few compelling advantages:
- Efficient data retrieval
- Dictionaries use hash tables behind the scenes which results in very fast retrieval of data based on keys.
- Code can be more concise because you can access data directly using keys.
- Organization and flexibility
- Dictionaries are, by their nature, structured. So this makes it easy to store a variety of data (e.g. strings alongside integers, booleans, lists, etc).