# DICTIONARIES

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):

# Create a Dictionary of months to abbreviations month_abbr = { 'January': 'Jan', 'February': 'Feb', 'March': 'Mar', 'April': 'Apr', 'May': 'May' } # Create a Dictionary of months to how many days they have month_days = { 'Jan': '31', 'Feb': '28', 'Mar': '31', 'Apr': '30', 'May': '31' }

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:

# Add some new months month_abbr['June'] = 'Jun' month_abbr['July'] = 'Jul' month_days['June'] = '30' month_days['July'] = '31'

We can access our entries and print out information:

# Print out information about the months print("Abbreviation for January is: ", month_abbr['January']) print("Abbreviation for February is: ", month_days['February']) print("# of Days in March: ", month_days['Mar']) print("# of Days in April: ", month_days['Apr'])

We can use information from one Dictionary to query another Dictionary:

# Print number of days the month print("# of Day in January: ", month_days[month_abbr['January']]) print("# of Day in Febuary: ", month_days[month_abbr['February']])

We can use a loop to print out all available Dictionary entries:

# Print months along with abbreviations and number of days for month, abbreviation in months_abbr.items(): print("The month", month, "is abbreviated", abbreviation, "and has", month_days[abbreviation], "days")