Lecture 23 — Dictionaries, Part 2

Overview

  • Recap.

  • More examples:

    • Dictionaries of string/set pairs

    • Converting dictionaries with one key to another

    • Combining information from multiple dictionaries

  • A different view of dictionaries: Nesting dictionaries.

Recap of dictionaries

  • On the surface, dictionaries look like lists, except, you can have anything for indices (keys), not just numbers starting with 0.

  • The power of a dictionary is that keys can be anything hashable.

Copying and Aliasing Dictionaries

  • We’ll take a few minutes in class for you to try to predict the output of the following:

    d = dict()
    d[1] = 'Hello'
    L = []
    L.append(d)
    d[2] = 'World'
    L.append(d.copy())
    d[1] = 'Hi'
    del d[2]
    print(L)
    
  • The result may surprise you, but it reflects the difference between making an alias to an object and making a full copy of an object.

    • An alias is also sometimes known as a shallow copy

    • A full copy is also sometimes known as a deep copy

  • Assignment between lists, between sets, and between dictionaries all involve aliasing / shallow copying!