In the concept, we discussed Lists, how they work and what they are good for. If you recall, Lists are great for storing an ordered sequence of items. For example, a list of names or a list of values. In a List, the sequence of the data is important, and each piece of data is an independent entity.
Sometimes though, you want to be able to associate certain pieces of data with other pieces of data. For example, you may have a list of people, and you want to associate each person's age with each name.
Here's an example:
NAME |
AGE |
---|---|
Bob |
22 |
John |
14 |
Alice |
36 |
Carol |
29 |
Alex |
64 |
Using a list to store this these associated pieces of data can be cumbersome. But, Python provides another mechanism that is perfect for storing data in this way — it's called a Dictionary. Just like a regular Dictionary that is use to map words to their definitions, a Python Dictionary maps "keys" (the first column) to their "values" (the second column).
Here's an example of how we could use Dictionaries in our code...
Imagine we wanted to make use of the months of the year, along with their abbreviations and the number of days they contain. We could create two Dictionaries — one that maps the months of the year to their abbreviations and another that maps the abbreviations to the number of days in that particular month.
Here is what the code to define these Dictionaries might look like (to keep things short, we won't use all the months):
Now that we have our Dictionaries created, we can perform a number of operations on them. Here are just a few examples of what we can do with our Dictionaries:
We can add more entries to our Dictionaries:
We can access our entries and print out information:
We can use information from one Dictionary to query another Dictionary:
We can use a loop to print out all available Dictionary entries: