Dictionaries & Sets

A Python dictionary is a un-ordered collection of Python objects (contrast with strings, lists, and tuples which are ordered sequences). What is new and particularly useful about dictionaries is that they can be indexed using any immutable object (unlike strings, lists and tuples that can only be indexed using integers). Because it is a collection (like strings, lists, and tuples) it shares characteristics such as iteration (for) and membership (in) as well as functions such as len(). Dictionaries are mutable (like lists).

A Python set is like a mathematical set that you should be familiar with: an un-ordered collection of unique objects. Set operations are the expected ones from mathematics: union, intersection, etc. Because it is a collection it shares characteristics such as iteration (for) and membership (in) as well as functions such as len(). Sets are mutable.

Readings from the book The Practice of Computing Using Python.

Chapter 9: Dictionaries & Sets

Videos

  1. Dictionaries
  2. A dictionary is a collection of pairs of Python objects: the pairs have the form key:value (note the colon ":"), the pairs are separated by commas and the collection is delimited by curly brackets. Any mixture of objects is allowed for a value; only an immutable can be a key.

    1. Dictionaries (Video I, Video II)
    2. Sets (Video I, Video II)
    3. Python sets are like mathematical sets: a collection of unique objects within curly braces.

    4. Comprehensions are a convenient way to build collections (Video )
  3. Examples using dictionaries
    1. Benford's Law (Video)
    2. Benford's Law (Wikipedia) refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the leading digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time.

  4. Patterns
  5. How to build a dictionary to count items:

                 a_dict = {}  # start with an empty dictionary
                 for item in collection:
                     if item not in a_dict:
                         a_dict[item] = 1  # initialize 
                     else: # item is in a_dict 
                         a_dict[item] += 1  # increment 
                  
    To build a dictionary of lists: initialize to an empty list and append.
  6. Chapter 9 Exercises on Mimir.
  7. Lab08 (do pre-lab first on D2L)
  8. Project07