Chapter 12 – Dictionaries

Sections 12.1 - 12.2

\(\boxdot\) Dictionaries
  • The collection or compound data types str, list and tuple have a sequential structure. You may access any element of the object by its index in the range [0, len(object)-1].

  • In many cases you probably do not know the meaning of the value with a given index. Does alist[2] give the name or age or street address of an individual?

  • In Python, a Dictionary is another data collection object that has a built-in mapping type.

  • A map is an unordered, associative pairing process.

  • For dictionaries, the mapping, or pairing, is between a key (any immutable object) and a value (any Python data object)

  • Constructing a dictionary - one way.

    d = {}          # define 'd' to be a dictionary indicated by the braces  
    d['Mark'] = 21  # the first key-value pair has the key 'Mark' and value 21
    print(d)
  • Activity 1: Write a function called make_dictionary(l) that takes the list l of tuples to generate a dictionary using the names as key words and the ages as values. Use the list below as the argument.

    a_list = [('Mark', 21), ('Angelo', 41), ('Wilson', 72), ('Roberta', 61), ('Xie', 19)]  
  • The value item in a dictionary can be a dictionary (just like a list may have an element that is a list). Copy and paste the line below into an active code window or pythontutor.com.

    d = {'first': 'Bob', 'last': 'White', 'age': 32, 'bday': {'day': 3, 'month': 5, 'year': 1997}}
  • Activity 2: Write a function that takes a string, such as the one below, and returns a dictionary with the structure shown in the line above. The five-digit number at the beginning of the string is the person’s ID number.

    info = "03459 Bob White 32 05/03/1997"   
  • Activity 3: Modify the code written in the previous activity so that it creates a dictionary of dictionaries. The dictionary entries in the main dictionary uses the person’s five-digit number at the beginning of the string as the person’s dictionary key.

    md = {03459 : {'first': 'Bob', 'last': 'White', 'age': 32, 'bday': {'day': 3, 'month': 5, 'year': 1997}}}
\(\boxdot\) Dictionary Operations
  • Delete a key-value pair:

    d = {'first': 'Bob', 'last': 'White', 'age': 32, 'bday': {'day': 3, 'month': 5, 'year': 1997}}  
    del d['age']
    print(d)  
  • Changing a dictionary value for a given key:

    d = {'first': 'Bob', 'last': 'White', 'age': 32, 'bday': {'day': 3, 'month': 5, 'year': 1997}}  
    d['age'] = 33
    print(d) 
    d['age'] += 1
    print(d)

Section 12.3

\(\boxdot\) Dictionary Methods
  • keys() - returns a view of a dictionary’s keys, that can be iterated over or converted to a list using the list() function

  • values() - returns a view of a dictionary’s values, that can be iterated over or converted to a list using the list() function

  • items() - returns a view of a dictionary’s key-value pairs, that can be iterated over or converted to a list of tuples using the list() function

  • get(key) - returns the value associated with the parameter key, none otherwise

  • get(key,_alt_) - returns the value associated with the parameter key, alt otherwise

  • Use the dictionary below to experiment with the various dictionary methods listed above.

    d = {'first': 'Bob', 'last': 'White', 'age': 32, 'bday': {'day': 3, 'month': 5, 'year': 1997}}  
  • Activity 4: Using a list comprehension, generate a list of random elements of integers or characters. Then use a dictionary to determine the count of each element in the list.

Sections 12.4 - 12.5

\(\boxdot\) Aliasing versus Copying
  • Dictionaries, like lists, are mutable, so you need to be aware of aliasing.

    d1 = {'first': 'Bob', 'last': 'White', 'age': 32, 'bday': {'day': 3, 'month': 5, 'year': 1997}}  
    d2 = d1  
    d2['age'] = 33  
    print(d1['age'])  
  • Use the copy() method to avoid unintended results

    d1 = {'first': 'Bob', 'last': 'White', 'age': 32, 'bday': {'day': 3, 'month': 5, 'year': 1997}}  
    d2 = d1.copy()  
    d2['age'] = 33  
    print(d1['age'])
    d2['bday']['day'] = 10
    print(d1['bday]['day'])
\(\boxdot\) Sparse Matrices
  • In Python, a matrix may be thought of as a list of sub-lists, where each sub-list is a row of the matrix, and the items of each sub-list are column entries of the given row. Example are shown below:

    m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  
    m2 = [[1, 2, 3, 4], [5, 6, 7, 8]]
  • Matrices are mutable because they are list of lists, and list are mutable.

    m1[2][0] = 1
    print(m1)  
  • There are common applications that use matrices, and many time the matrix is sparse in that it has few non-zero entries.

    m3 = [[0, 3, 0], [1, 0, 0], [0, 0, -2]]  
  • A dictionary can provide an efficient way to represent a sparse matrix.

    d_m3 = {(0, 1): 3, (1, 0): 1, (2, 2): -2}  
    m3 = [[0]*3]*3
    for akey in d_m3.keys():
        m3[akey[0]][akey[1]] = d_m3[akey]  
  • Another try…

    d_m3 = {(0, 1): 3, (1, 0): 1, (2, 2): -2}  
    m3 = [[0]*3, [0]*3, [0]*3]
    for akey in d_m3.keys():
        m3[akey[0]][akey[1]] = d_m3[akey] 
  • Coding solution for Assignment 28:

    def sparse_fill(d, r, c):
        m = []
        ec = 0
        for row in range(r):
            m.append([0]*c)
        for akey in d:
            if akey[0] >= r and akey[1] < c:
                ec = 1
            elif akey[0] < r and akey[1] >= c:
                ec = 2
            elif akey[0] >= r and akey[1] >= c:
                ec = 3
            else:
                m[akey[0]][akey[1]] = d[akey]
        return m, ec