Dictionaries#

Type

dict

Synatx

{item,...}

Bases

Mapping

State

Mutable

Position

Ordered

Composition

Heterogeneous

Diversity

Repeatable

Access

Subscriptable

Value

Not hashable

Introduction#

A dictionary is a collection of key value pairs. Each key is connected to a value, which makes it easy to look up a particular value.

A dictionary is kind of like a phone book, where you can look up someone’s phone number (the value) using their name (the key). Or an English dictionary where the you can look up a word (the key) to get its meaning (the value).

Creating#

To create a dictionary, enclose comma-separated key value pairs in curly braces { } with a : between each key and value.

book = {
  "title": "Last Chance to See",
  "author": "Douglas Adams",
  "year": 1990,
}

A visualization of that dictionary would look something like this:

+----------------------+-----------------------+-----------------------+ |       "title"   cCFF |       "author"   cCFF |        "year"     cCFF| +----------------------+-----------------------+-----------------------+ |                      |                       |                       | | "Last Chance to See" | "Doublas Adams"       | 1990                  | |                      |                       |                       | +----------------------+-----------------------+-----------------------+    /----\   |cCFF| key   \----/

Exercise 50 (Shapes Dictionary)

Create a dictionary assigned to the variable shapes that uses shape names (like "square" or "triangle") for keys and the number of sides (like 4 and 3) for values.

Print the dictionary.

Accessing#

Items are accessed via subscription, using [ ] after the object to enclose the key.

print("Title:", book["title"])
print("Author:", book["author"])
print("Published:", book["year"])
Title: Last Chance to See
Author: Douglas Adams
Published: 1990

If you try to access a key that does not exist, you will encounter a KeyError.

print("Series:", book["series"])
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[3], line 1
----> 1 print("Series:", book["series"])

KeyError: 'series'

However, you can avoid this using the .get() method, which takes two arguments: the key, and an optional default value. If the key is in the dictionary, it will return the associated value.

author = book.get("author", "Anonymous")
print("Author:", author)
Author: Douglas Adams

Otherwise, the value passed for the default argument will be returned.

series = book.get("series", "NA")
print("Series:", series)
Series: NA

Exercise 51 (Lookup Sides)

Use subscription to print "A name has number sides." for a square and rectangle.

Listing 175 example output#
A triangle has 3 sides.
A square has 4 sides.

Exercise 52 (Lookup Side with Fallback)

Prompt the user for the shape name, then look up the number of sides in shapes using the .get() method.

If the shape is not in the dictionary print: "Sorry, I don't know the shape: name"

Otherwise print: "A name has number sides."

Listing 177 example output
(when the key is in shapes)
#
shape > rectangle
A rectangle has 4 sides.
Listing 178 example output
(when the shape is missing)
#
shape > heart
Sorry, I don't know the shape: heart

Modifying#

Adding or changing elements in the list is done the same way, also using subscription.

from pprint import pprint

book["genre"] = "Nonfiction"
book["author"] = "Douglas Adams, Mark Carwardine"

pprint(book, sort_dicts=False)
{'title': 'Last Chance to See',
 'author': 'Douglas Adams, Mark Carwardine',
 'year': 1990,
 'genre': 'Nonfiction'}

You can also change multiple elements at once using the .update() method, which takes one argument, a dictionary. Any keys already present in the original dictionary will be changed, and any not in the original dictionary will be added. The remaining elements will be left as they are.

book.update({"isbn": "0345371984", "genre": "Science", "pages": 256})

pprint(book, sort_dicts=False)
{'title': 'Last Chance to See',
 'author': 'Douglas Adams, Mark Carwardine',
 'year': 1990,
 'genre': 'Science',
 'isbn': '0345371984',
 'pages': 256}

Exercise 53 (Add and Change a Shape)

Use subscription to:

  • add the shape "oval" to shapes with 0 sides

  • change "square" to "four" sides

Exercise 54 (Add and Change Multiple Shapes)

Use the .update() method to

  • change "triangle" to "three" sides

  • add star with 10 sides

  • add nonagon with 9 sides

Removing#

To remove elements you can use the del keyword.

del book["pages"]

pprint(book)
{'author': 'Douglas Adams, Mark Carwardine',
 'genre': 'Science',
 'isbn': '0345371984',
 'title': 'Last Chance to See',
 'year': 1990}

You can also remove items using the .pop() method, which returns the deleted element before removing it.

isbn = book.pop("isbn")
print("The books ISBN is:", isbn)
pprint(book)
The books ISBN is: 0345371984
{'author': 'Douglas Adams, Mark Carwardine',
 'genre': 'Science',
 'title': 'Last Chance to See',
 'year': 1990}

Just like when using subscription, .pop() will raise a KeyError if no value with that key exists.

fmt = book.pop("format")
print("This books format is:", fmt)
pprint(book)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[10], line 1
----> 1 fmt = book.pop("format")
      2 print("This books format is:", fmt)
      3 pprint(book)

KeyError: 'format'

You can avoid this error by pass the optional second argument default. This works just like the default argument in the get method–the key value pair will be removed if it exists.

year = book.pop("year", "Unknown")
print("The year is:", year)
pprint(book)
The year is: 1990
{'author': 'Douglas Adams, Mark Carwardine',
 'genre': 'Science',
 'title': 'Last Chance to See'}

If it doesn’t exist, the value passed as the default argument will be returned instead.

fmt = book.pop("format", "Unknown")
print("The format is:", fmt)
pprint(book)
The format is: Unknown
{'author': 'Douglas Adams, Mark Carwardine',
 'genre': 'Science',
 'title': 'Last Chance to See'}

Exercise 55 (Remove a Shape)

Print shapes then remove the "star" shape using del. Print shapes again to confirm it has been removed.

Exercises#

Exercise 56 (Word calculator)

Make a dictionary of numbers where the keyword is a word (like "one") and the value is an integer (like 1). Assign it to the variable numbers.

Write an add() function that takes two string arguments, adds together the value in the numbers dictionary associated with those keys, and returns the result.

Example Usage

>>> add("one", "three")
4

Solution template

def add(a, b):
  """Add the value of two number strings.

  >>> add("one", "three")
  4
  """

Exercise 57 (Scrabble Score)

In this exercise you’ll write a function that calculates the scrabble score for a list of letters.

  1. Make a dictionary assigned to the global variable POINTS where each key is a letter with a value of the cooresponding point, as listed below.

    Points

    Letters

    1

    A, E, I, L, N, O, R, S, T and U

    2

    D and G

    3

    B, C, M and P

    4

    F, H, V, W and Y

  2. Write a function score() that takes one argument, a string or list of letters. Use the POINTS dictionary to look up the value of each letter and add them together, then return the total.

    Need a hint?
    • set a variable total to 0

    • iterate over each letter in the list

      • get the point value for each letter from the POINTS dictionary

      • add it to total

    • return total

Example Usage

>>> score("blank")
11
>>> score(["d", "i", "r", "t"])
5

Solution template

def score(letters):
    """Return the scrabble score for a list of letters
    >>> score("blank")
    11
    >>> score("dirt")
    5
    >>> score("fajita")
    16
    """

Membership#

Keys and values#

You can get a list of all of the keys in a dictionary using the .keys() method.

print(book.keys())
dict_keys(['title', 'author', 'genre'])

Similarly, you can get a list of all of the values in a dictionary using the .values() method.

print(book.values())
dict_values(['Last Chance to See', 'Douglas Adams, Mark Carwardine', 'Science'])

Both of these are iterables which can be converted to a list.

keys = list(book.keys())
pprint(keys)

values = list(book.values())
pprint(values)
['title', 'author', 'genre']
['Last Chance to See', 'Douglas Adams, Mark Carwardine', 'Science']

Key types#

The book dictionary uses strings for keys, but you can actually use nearly any type as a key.

numbers = {
  10: "ten",
  20: "twenty",
  30: "thirty",
}

print(numbers[30])
thirty

You can mix and match the type of keys.

numbers = {
  10: "ten",
  20: "twenty",
  30: "thirty",
  0.5: "half",
  0.25: "a quarter",
  0.125: "one eighth",
}

print(numbers[0.5])
half

You can even use a tuple objects as keys.

times = {
  (12, 0): "noon",
  (8, 30): "half past eight",
  (24, 0): "midnight",
  (9, 45): "quarter to nine",
}

print(times[(8, 30)])
half past eight

You just can’t use mutable objects as keys, like dict or list objects.

times = {
  [12, 0]: "noon",
}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[19], line 1
----> 1 times = {
      2   [12, 0]: "noon",
      3 }

TypeError: unhashable type: 'list'

Conditions#

You can check if a dictionary has a particular key using the in operator.

>>> "title" in book
True
>>> "series" in book
False

To check if a dictionary has a particular value you’ll also use the in operator, but on the .values() method.

>>> 1990 in book.values()
True
>>> "Orson Scott Card" in book.values()
False

Nested values#

Values can be anything you want, even other dictionaries or lists.

favorites = {
  "jessica": {
    "color": "purple",
    "movie": "Pulp Fiction",
    "book": "The Lion, the Witch and the Wardrobe",
    "song": "Another One Bites the Dust",
  },
  "eric": {
    "color": "green",
    "movie": "Goodfellas",
    "book": "The Lion, the Witch and the Wardrobe",
    "song": "Good Vibrations",
  }
}

You can access items in the nested lists by using multiple subscription operations, with brackets back to back.

print("Jessica's favorite book is:", favorites["jessica"]["book"])
Jessica's favorite book is: The Lion, the Witch and the Wardrobe

Another way to do this is to retrieve each level and store it in a variable.

jessica = favorites["jessica"]
print("Jessica's favorite book is:", jessica["book"])
Jessica's favorite book is: The Lion, the Witch and the Wardrobe