Dictionaries

Outside Resources:

TheNewBoston – Dictionaries

Snakify – Dictionaries

LearnPython.org – Dictionaries

W3Schools – Dictionaries


Dictionaries are like lists, except the items are named instead of numbered. This is convenient when the names are more relevant than the numbers or the order of the items.

Dictionaries store key : value pairs.

This dictionary stores prices of items at a restaurant:

#create a dictionary
prices = {'cake': 3.50, 'coffee': 1.95}

#add another item
prices['pastry'] = 2.75

Notice that the key and value are separated by a colon for each entry. Entries are comma separated.

In the example, the key is the text description of the item. The value is the price in the example. The keys can be numbers, if desired. The values can be any Python data type, including numbers, strings, lists, dictionaries, and other types of objects.

Looking up Values

Method 1: square brackets

p1 = prices['cake']
print(prices['coffee'])

Method 2: dict.get()

p1 = prices.get('cake')
print(prices.get('coffee'))

The two method work the same, except when the key doesn’t exist in the dictionary. If your program might look up a value that doesn’t exist, use the get() method to avoid crashes.

a = prices.get('blarfqz')
RESULT:
[nothing happens]

a = prices['blarfqz']
RESULT:
Traceback (most recent call last):
  File "<input type="text" />", line 1, in 
KeyError: 'blarfqz'

Notice that the text literals are in quotes, because the keys are strings. You can also look up a key that is stored as a variable:

x = 'coffee'
print(prices[x])

You can loop through a dictionary. This will print every description and price. The variable x becomes each key in the dictionary as the loop repeats. The value is prices[x].

for x in prices:
    print(x, prices[x])

Another loop example: This raises the prices of every item by 0.50:

for x in prices:
    prices[x] += 0.50

You can check if an item exists in the dictionary:

if 'fries' in prices:
    print('Fries are on the menu.')
else:
    print('Sorry, we do not sell fries.)

Deleting a key from a dictionary:

# Two different ways to do this:
del prices['cake']
prices.pop('cake')

You might want to check if that item exists first before you try deleting it. Deleting something that doesn’t exist causes an error.

old_item = 'cake'
if old_item in prices:
    del prices[old_item]

You can make a list out of the dictionary’s keys or values if needed.

products = list(prices.keys())
pricelist = list(prices.values())

Dictionary keys and values from a global dictionary can be accessed and modified from within a function without declaring them as global in the function. This can be a useful way to access and modify information from different functions without dealing with a bunch of global variables.