Dictionaries

Are:

  • mutable
  • keys must be hashable
    • this meaning functions can actually be keys
  • have fun methods like pop() and popitem() for removing keys
  • support nesting
  • don’t support nested membership tests
1
2
3
4
5
f = {1: 'value', len: 1, 'str': (1j-3) }
self.assertEqual(f[1], 'value')
self.assertEqual(type(f[1]), str )
self.assertEqual(type(f[len]), int )
self.assertEqual(type(f['str']), complex )

Sets

Oh. boy. First class support for sets 🤩 wow, I’m so excited!

OperatorMethod NameNote
|unionIs a set of all elements in either set.
&intersectionIs a set of all the common elements between either set.
-differenceIs a set of all elements that are in x1 but not in x2.
^symmetric_differenceIs a set of all elements in either x or x2, but not both.
<=issubsetIf every element of x1 is in x2.
<If proper subset, like subset, but only if it is not identical to itself.
>=issupersetIf x1 contains every element of x2.
>If proper superset, like superset, but only if it is not identical to itself.
|=updateAdd to x1 any elements in x2 that x1 does not already have.
&=intersection_updateUpdate x1 to retain only elements found in both x1 and x2
-=difference_updateUpdate x1, removing elements found in x2
^=symmetric_difference_updateUpdate x1, retaining elements found in either x1 or x2, but not both.

frozenset type is immutable, so it can be used as a dictionary key.

The biggest value of using sets is their speed, they’re way faster to iterate through than lists and tuples.

Repl of the Day