Today: 1. When do you get a copy? with =? With parameters? 2. dict-count algorithm. 3. More sophisticated dict nesting - file index example

Python and Copying

We'll need to lean harder today on how Python's lack of copying memory. When using =, when passing a parameter - not a copy.

>>> d = {}
>>> d['a'] = [1, 2]
>>> lst = d['a']

lst is a reference to the list nested inside the dict - not a separate list, the same list. So if we append on lst, it is changing the list inside the dict.

>>> lst = d['a']
>>> lst.append(3)
>>> lst
[1, 2, 3]
>>> 
>>> d     # Now the list inside of d has been changed
{'a': [1, 2, 3]}

For more detail see guide: Python Not Copying

Dict-Count Algorithm

Dict Count Code Examples

> Dict Count Examples

Dict-Count Steps

1. str-count1() - if/else

str_count1 demo, canonical dict-count algorithm

Solution code

def str_count1(strs):
    counts = {}
    for s in strs:
        # s not seen before?
        if s not in counts:
            counts[s] = 1   # first time
        else:
            counts[s] += 1  # every later time
    return counts

2. str-count2() - "Invariant" Version, no else

Standard Dict-Count Code - "invariant" Version

def str_count2(strs):
    counts = {}
    for s in strs:
        if s not in counts:  # fix counts/s if not seen before
            counts[s] = 0
        # Invariant: now s is in counts one way or
        # another, so can do next step unconditionally
        counts[s] += 1
    return counts

Int Count - Exercise

Apply the dict-count algorithm to a list of int values, return a counts dict, counting how many times each int value appears in the list.

Char Count - Exercise

Apply the dict-count algorithm to chars in a string. Build a counts dict of how many times each char appears in a string so 'Coffee' returns {'c': 1, 'o': 1, 'f': 2, 'e': 2}.


Dict-Count Chapter 1 Summary - Init/Incr

Suppose "x" holds the key we're counting...

    if x not in counts:   # Fix so x is in there
       counts[x] = 0      # -Init
    counts[x] += 1        # -Increment

Dict - Chapter 2 - Nested

Email Hosts Data

Email Hosts Outline

Given a list of email address strings. Each email address has one '@' in it, e.g. 'abby@foo.com', where 'abby' is the user, and 'foo.com' is the host.

Create a nested dict with a key for each host, and the value for that key is a list of all the users for that host, in the order they appear in the original list (repetition allowed).

emails:
  ['abby@foo.com', 'bob@bar.com', 'abe@foo.com']

returns hosts dict:
  {
   'foo.com': ['abby', 'abe'],
   'bar.com': ['bob']
  }

Nested - Key/Value Types

When working a nested dict problem, it's crucial to keep in mind the type of each key and its value. This info guides code that reads or writes in the dict. In this case (peek above), each key is a host, and its value is a list of user strings.

Email Parse Code

Here is the code snippet to extract the user/host from an email:

        at = email.find('@')
        user = email[:at]
        host = email[at + 1:]

Nested Hosts Example

> email-hosts Problem

Build up a list for each key. Old init was: 0. Now the init is: []. Sketch out the state of the hosts dict, work on the lines of code to add to it.

Issue: hosts[host]

This line is very hard to read, like what on earth is it?

Recall that the hosts dict looks like:

  {
   'foo.com': ['abby', 'abe'],
   'bar.com': ['bob']
  }

In hosts dict, each key is a host, and each value is a list of user names.

Style Technique: Decomp By Var

Instead of using hosts[host] as is, put its value into a well named var, spelling out what sort of data it holds. This is a big help and is how our solution is written. Note how the names in this line of code confirm that the logic is correct: users.append(user) This depends on the "shallow" feature of Python data (above), e.g. hosts[host] returns a reference to the embedded list to us.

No:

    hosts[host].append(user)

Yes:

    users = hosts[host]
    users.append(user)

Nested Hosts Solution Code

def email_hosts(emails):
    hosts = {}
    for email in emails:
        at = email.find('@')
        user = email[:at]
        host = email[at + 1:]

        # key algorithm: init/increment
        if host not in hosts:
            hosts[host] = []
        users = hosts[host]  # decomp by var
        users.append(user)
    return hosts

Need today: line.split() -> list

>>> line = ' this      and  that. '
>>> line.split()
['this', 'and', 'that.']

Bigger Nested Dict Exercise - Index

> index.zip

Example Index Dict

File tea-time.txt 2 lines:

tea time
coffee time

Example index. Key for each word. Value for each is key is list of lines containing that word. The dict totally captures the text. Note how keys are in a random order.

1. When just line 1 tea time is indexed:

{
'tea': ['tea time'],
'time': ['tea time'],
}

2. State when line 2 coffee time is added:

{
'tea': ['tea time'],
'time': ['tea time', 'coffee time'],
'coffee': ['coffee time']
}

Program output is just a prettied up version of the dict. Prints the words in sorted order (code below). Puts '**' around each key word, followed by its lines. The function to make this output from the dict is provided.

**coffee**
coffee time

**tea**
tea time

**time**
tea time
coffee time

Gettysburg Output

Gettysburg address output
...
**which**
living, rather, to be dedicated here to the unfinished work which they
which they gave the last full measure of devotion -- that we here

**who**
portion of that field, as a final resting place for those who here
who struggled here, have consecrated it, far above our poor power to
who fought here have thus far so nobly advanced. It is rather for us

**will**
add or detract. The world will little note, nor long remember what we
....

index_line(index, line)

Types in index dict

index_line(index, line) - Write The Code

def index_line(index, line):
    """
    Given an index dict and a line of text,
    update the index with the text of that line
    and return the modified dict.
    Use the lowercase form of each word as the key.
    >>> index_line({}, 'tea time')
    {'tea': ['tea time'], 'time': ['tea time']}
    >>> index_line({'tea': ['tea time'], 'time': ['tea time']}, 'coffee time')
    {'tea': ['tea time'], 'time': ['tea time', 'coffee time'], 'coffee': ['coffee time']}
    """
    words = line.split()
    for word in words:
        word = word.lower()
        # Your code here - update index for each word
        pass
        
    return index

index.py Solution Code

"""
Stanford CS106A Index Example
Nick Parlante
Shows reading all the words out of a file,
building a "nested" dict structure to analyze them,
printing out the contents of a dict with a standard
sorted(d.keys()) loop.
"""

import sys


"""
We'll say that an "index" dict has a key for the lowercase
version of every word in a text, and its value
is a list of all the lines where that word appears.
"""


def index_line(index, line):
    """
    Given an index dict and a line of text,
    update the index with the text of that line
    and return the modified dict.
    Use the lowercase form of each word as the key.
    >>> index_line({}, 'tea time')
    {'tea': ['tea time'], 'time': ['tea time']}
    >>> index_line({'tea': ['tea time'], 'time': ['tea time']}, 'coffee time')
    {'tea': ['tea time'], 'time': ['tea time', 'coffee time'], 'coffee': ['coffee time']}
    """
    words = line.split()
    for word in words:
        word = word.lower()
        # Your code here - update index for each word
        pass
        if word not in index:
            index[word] = []
        lines = index[word]  # Style idea: decomp by var
        lines.append(line)
    return index
    # Extension: avoid listing a line mult times per word:
    #   if line not in lines: lines.append(line)


def index_file(filename):
    """
    (provided)
    Given filename, build and return index of its contents.
    (just calls index_line() for every line)
    """
    # Build the index with every line from file
    index = {}
    with open(filename) as f:
        for line in f:
            index_line(index, line)
            # Each call to index_line() modifies the index dict
    return index


def print_index(index):
    """
    (provided)
    Given index dict, print out its contents.

    Print out the words in alphabetical order.
    Each word with **'s as shown below,
    followed by all the lines where that word appears,
    followed by a blank line.
    e.g. here is part of the gettysburg address index output

    **who**
    portion of that field, as a final resting place for those who here
    who struggled here, have consecrated it, far above our poor power to
    who fought here have thus far so nobly advanced. It is rather for us

    **will**
    add or detract. The world will little note, nor long remember what we
    """
    # Standard loop to dump out a dict by going through
    # all the keys in sorted order.
    for word in sorted(index.keys()):
        print('**' + word + '**')
        lines = index[word]       # decomp by var
        for line in lines:
            print(line, end='')   # line already has \n
        print()                   # print a blank line


def main():
    args = sys.argv[1:]
    # args: -filename-   - prints index of that text file
    if len(args) == 1:
        index = index_file(args[0])
        print_index(index)

Run

$ python3 index.py tea-time.txt
**coffee**
coffee time

**tea**
tea time

**time**
tea time
coffee time

$ python3 index.py gettysburg.txt
...
lots
...
**who**
portion of that field, as a final resting place for those who here
who struggled here, have consecrated it, far above our poor power to
who fought here have thus far so nobly advanced. It is rather for us

**will**
add or detract. The world will little note, nor long remember what we

**work**
living, rather, to be dedicated here to the unfinished work which they

**world**
add or detract. The world will little note, nor long remember what we

**years**
Four score and seven years ago our fathers brought forth on this

Loop over a dict - d.keys() (May get to this)

>>> d = {'a': 'alpha', 'g': 'gamma', 'b': 'beta'}
>>> d.keys()
dict_keys(['a', 'g', 'b'])  # not alphabetic order

The following loop works to iterate over whole dict. Don't need to check "in" for each key - these are the keys.

for key in d.keys():
    # use key and d[key] in here
    print(key, d[key])

Standard Loop Over Dict - sorted(d.keys())

>>> d = {'a': 'alpha', 'g': 'gamma', 'b': 'beta'}
>>> sorted(d.keys())
['a', 'b', 'g']       # in alphabetic order, loop over this

Standard loop to see contents of dict in order. Look at print_index() above as a filled out example of this pattern.

for key in sorted(d.keys()):
    print(key, d[key])