Python

Dictionaries

Organizing information in dictionaries

What is a Dictionary?

Another way to group information in Python is through a dictionary. A dictionary in Python consists of keys and values. The key is on the left side, and the value is on the right. Dictionaries allow us to create more descriptive lists. Instead of accessing a value by an index number, we can access it using a descriptive ‘key’.

Syntax

The syntax of a dictionary is as follows…

dict_name = {
    “Key1”: ”value1”,
    “Key2”: “value2”,
}

For example...

address = {
    “Line 1”: “1234 ABCD St”,
    “Line 2”: “”,
    “State”: “TX”,
    “Postal Code”: “75021”
}

In this dictionary, each section of the address is given a key, and has its own value. It is a much clearer way of representing information, compared to, say, a list. But, lists have their own purposes.

Accessing Dictionaries

To access a value of a dictionary, simply follow the format ‘dict_name[key]’. For our address dictionary…

address = {
    “Line 1”: “1234 ABCD St”,
    “Line 2”: “”,
    “State”: “TX”,
    “Postal Code”: “75021”
}
postal_code = address[“Postal Code”]

print("Postal Code: " + postal_code)    

Output:

Postal Code: 75021

Here, we accessed the postal code of the address by using the key “Postal Code” in the ‘address’ dictionary. The name may be confusing, but if you think about it, this is how actual dictionaries work too. You look up a meaning (value) by searching for the word (key).

chevron_up