Sets and Dictionaries

Overview

Teaching: 10 min
Exercises: 5 min
Questions
  • What is a set?

  • What is a dictionary?

Objectives
  • Explain the features of sets and dictionaries.

  • Understand how dictionaries map keys to values

  • Learn how to add and get items from sets and dictionaries.

Sets

Sets are unordered collections of unique items

set1 = set("abc")
set2 = set("acb")
set3 = set("aabbbcc")
print(set1, set2, set3)
{'b', 'c', 'a'} {'b', 'c', 'a'} {'b', 'c', 'a'}
my_set = {'a', 'b', 'c'}
my_set.add('d')
print(my_set)

my_set.update({'e', 'f', 'g'})
print(my_set)
{'a', 'c', 'd', 'b'}
{'f', 'g', 'b', 'e', 'c', 'd', 'a'}
some_set = set(['UGA', 'UAG', 'UAA'])
print(some_set)
print(some_set.pop())
print(some_set)
{'UAG', 'UAA', 'UGA'}
UAG
{'UAA', 'UGA'}

What objects can go in a set?

Surprisingly, not every type of object can be added to a set

my_set = {[1, 2]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-bf858b2308e0> in <module>()
----> 1 my_set = {[1, 2]}
 
TypeError: unhashable type: 'list'
  • The error means that python cannot add a list to a set
  • Only objects that cannot change can be added to sets

Dictionaries

Dictionaries add meaningful labels

name = {'first': 'Paul', 'last': 'Wilson'}
print(name['first'], name['last'])
name['last'] = 'Nagus-Wilson'
print(name['first'], name['last'])
Paul Wilson
Paul Nagus-Wilson

Entries can be added to a dictionary

my_name = {'first': 'Paul', 'last': 'Wilson'}
my_name['middle'] = 'Philip'
print(my_name)
my_name['last'] = 'Nagus-Wilson'
print(my_name)
your_name['first'] = 'Henry'
{'first': 'Paul', 'last': 'Wilson', 'middle': 'Philip'}
{'first': 'Paul', 'last': 'Nagus-Wilson', 'middle': 'Philip'}
--------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-97-cc04cabb3603> in <module>()
      1 my_name = {'first': 'Paul', 'last': 'Wilson'}
      2 my_name['middle'] = 'Philip'
----> 3 your_name['first'] = 'Henry'

NameError: name 'your_name' is not defined

Use del to remove items from a dictionary entirely.

my_name = {'first': 'Paul', 'middle': 'Philip', 'last': 'Wilson'}
print(my_name)
del my_name['middle']
print(my_name)
{'first': 'Paul', 'middle': 'Philip', 'last': 'Wilson'}
{'first': 'Paul', 'last': 'Wilson'}

Various ways to access all the entries in a dictionary

name = {'first': 'Paul', 'last': 'Wilson'}
print(name.keys())
print(name.values())
dict_keys(['first', 'last'])
dict_values(['Paul', 'Wilson'])

Key Points

  • A set is an unordered, unique collection of immutable objects.

  • A dictionary is a mapping between objects, from keys to values.

  • Dictionary keys must be immutable.

  • Get a value from a dictionary with my_dict[some_key]. Add an item with my_dict[some_key] = some_value.

  • Dictionaries and sets are mutable.