Dictionaries

Dictionary Basics

Dictionaries are unordered key-value pairs. Like a real dictionary, we can look up something (a word in a language dictionary), and see some kind of information associated with it.

>>> clothing = {'hat': 'a shaped covering for the head',
                'shirt': 'a long- or short-sleeved garment for the upper part of the body'}
>>> clothing
{'shirts': 3, 'shoes': 2}

We can retrieve particular values based on their key:

>>> clothing['hat']
a shaped covering for the head

Let’s look at using a dictionary to track how many pieces of clothing we have, instead of the definitions of those pieces of clothing.

>>> clothing = {'shoes': 2, 'shirts': 3}
>>> clothing
{'shirts': 3, 'shoes': 2}
>>> clothing['shoes']
2
>>> clothing['shirts']
3

What else can we do with dictionaries? We can add or update key-value pairs:

>>> clothing['socks'] = 6
>>> clothing
{'socks': 6, 'shirts': 3, 'shoes': 2}
>>> clothing['socks'] = 8
>>> clothing
{'socks': 8, 'shirts': 3, 'shoes': 2}

We can remove key-value pairs too:

>>> del clothing['shoes']
>>> clothing
{'socks': 8, 'shirts': 3}

What happens if we try to access a key that doesn’t exist?

>>> clothing['shoes']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'shoes'

If we loop over a dictionary, it will only loop over the keys:

>>> for item in clothing:
...     print(item)
...
socks
shirts

If we want to loop over key-value pairs, we can use the items method:

>>> for article, count in clothing.items():
...     print("I have {} {}".format(count, article))
...
I have 8 socks
I have 3 shirts

Dictionary Behavior

When you check a dictionary for containment, it will check the keys, but not the values:

>>> ages = {4: 2, 3: 1}
>>> 4 in ages
True
>>> 1 in ages
False

Dictionaries are truthy if they contain any key-value pairs and falsey if they are empty:

>>> things = {}
>>> if not things:
...     print("There are no things")
...
There are no things
>>> things['hat'] = 2
>>> things
{'hat': 2}
>>> if not things:
...     print("There are no things")
...

The list, int, and str, functions we already learned about are actually constructors:

>>> list()
[]
>>> int()
0
>>> str()
''

Dictionaries also have a constructor called dict.

>>> dict()
{}
>>> help(dict)

Dictionaries can be created from lists of two-item tuples (or lists of any two-item iterables):

>>> letters = [('a', 0), ('b', 1)]
>>> letter_dict = dict(letters)
>>> letter_dict
{'a': 0, 'b': 1}

The reverse of this is the items method, that extracts the key-value pair items of the dictionary:

>>> letter_dict.items()
dict_items([('a', 0), ('b', 1)])

Notice that a list isn’t returned from this:

>>> letter_items = letter_dict.items()
>>> type(letter_items)
<class 'dict_items'>

For performance reasons, Python 3 often returns collections that are not regular lists. You can iterate over these collections as usual and in general they act just like lists.

If you need an actual list, you can always pass an iterable into a list constructor:

>>> list(letter_items)
('a', 0), ('b', 1)]

Your Turn: Dictionaries 🏁

Dictionary Exercises

Rock, Paper, Scissors, Spock, Lizard

Building on the rock, paper, scissors exercise from earlier, create a new program rpssl.py for playing rock, paper, scissors, Spock, lizard game against the computer, using a dictionary to determine the winner. It should work like this:

  1. Set a move for the computer to make.
  2. Ask for a move from the user.
  3. Print the winner.

You can refer to the original creator notes for rules.

Bonus:

  1. Account for upper- and lower-case input
  2. Deal with cases when the user input is an invalid choice