Today: talk about midterm a tiny bit, more next week. Main topic: Dictionaries, dict-count algorithm

Dict - Hash Table - Fast

Python Dict - Advanced

Python Dict

See also: Python Dict

alt:python dict key/value pairs 'a'/'alpha' 'g'/'gamma' 'b'/'beta'

First Dict Code Example

>>> d = {}             # start as empty dict {}
>>> d['a'] = 'alpha'   # store key/values into d
>>> d['g'] = 'gamma'
>>> d['b'] = 'beta'
>>> d
{'a': 'alpha', 'g': 'gamma', 'b': 'beta'}  # curly-brace syntax
                                           # order is somewhat random
>>> d['b']
'beta'
>>> d['a'] = 'apple'   # overwrite 'a' key
>>> d['a']
'apple'
>>> d['x']
Error:KeyError('x',)
>>> 'a' in d
True
>>> 'x' in d
False
>>> # Use += to modify
>>> d['a'] += '!!!'
>>> d['a']
'apple!!!'
>>> 
>>> # Can write dict literal with { } syntax
    # style: 1 space after colon and comma
>>> d = {'a': 'alpha', 'g': 'gamma', 'b': 'beta'}

Dict = Memory

Dict Memory Example

Use dict to remember that 'snack1' is 'apple' and 'snack2' is 'donut'. Using 'snack1' and 'snack2' as keys.

>>> d = {}
>>> d['snack1'] = 'apple'
>>> d['snack2'] = 'donut'
>>>
>>> # time passes, other lines run
>>>
>>> # what was snack2 again?
>>> d['snack2']
'donut'
>>> 

Dict-Count Algorithm

Dict-Count Steps

1. str-count1() - if/else

str_count1 demo, canonical dict-count algorithm

> 1.str-count1

Solution code

def str_count1(strs):
    counts = {}
    for s in strs:
        # s first time?
        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

> 2. str-count2

Standard Dict-Count Code - "invariant" Version

def str_count2(strs):
    counts = {}
    for s in strs:
        if s not in counts:  # make s be in there
            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 - You Try It

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.

> 3. int-count