Dictionaries

Dictionaries#

A dictionary is a mapping from a key to a value. It is kind of like a list of pairs.
We can create dictionaries using curly braces — {}.
As with lists, commas separate elements in dictionaries.
Notice how each element is a pair of values separated by a colon:

starbucks_dict = {'price': 83, 'name': 'Starbucks Corp', 'ticker': 'SBUX', 'public': True}
starbucks_dict
{'price': 83, 'name': 'Starbucks Corp', 'ticker': 'SBUX', 'public': True}

We can also place elements on separate lines to make the dictionary more readable. This does exactly the same thing. Just do not forget the commas.

Since there is nothing after 'public': True a comma is not necessary. However, including one does not hurt anything, and might help you avoid an error if you come back later and add another line.

starbucks_dict = {
    'price': 83,
    'name': 'Starbucks Corp',
    'ticker': 'SBUX',
    'public': True,
}
starbucks_dict
{'price': 83, 'name': 'Starbucks Corp', 'ticker': 'SBUX', 'public': True}

We can access individual values from the dictionary using square brackets that contain the key:

print(starbucks_dict['price'])
print(starbucks_dict['name'])
83
Starbucks Corp

We could have stored the same information in a list:

starbucks_list = [83, 'Starbucks Corp', 'SBUX', True]

But then we would have to remember that the first element is the price, the second element is the name, etc. It is much easier to instead use a dictionary, where we can use the key to access the value.

You can also add a new mapping, or pair, to the dictionary.
Or even change the value of an existing entry.

starbucks_dict['ceo'] = 'Narasimhan'
starbucks_dict['price'] = 99

starbucks_dict
{'price': 99,
 'name': 'Starbucks Corp',
 'ticker': 'SBUX',
 'public': True,
 'ceo': 'Narasimhan'}

We can also define a dictionary using dict() instead of curly braces:

walmart_dict = dict(
    price = 160,
    name = 'Walmart Inc',
    ticker = 'WMT',
    public = True,
    ceo = 'McMillon',
)
walmart_dict
{'price': 160,
 'name': 'Walmart Inc',
 'ticker': 'WMT',
 'public': True,
 'ceo': 'McMillon'}

This approach is arguably easier to type and read, but it does come with a small downside. You cannot use spaces in your keys. For example, in this dictionary we have a key named latest price, which would not be possible with the dict() approach.

new_dict = {
    'latest price': 42,
}