Today: dict and dict-count

Dict - Hash Table - Fast

Python Dict - Advanced

Python Dict

For more details see guide: 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'}

Key and Value - Different Roles

Dict = Memory

Dict vs. List - Keys

Dict Memory Example - Meals

Use dict to remember that 'breakfast' is 'apple' and 'lunch' is 'donut'. Using 'breakfast' and 'lunch' as keys.

>>> d = {}
>>> d['breakfast'] = 'apple'
>>> d['lunch'] = 'donut'
>>>
>>> # time passes, other lines run
>>>
>>> # what was lunch again?
>>> d['lunch']
'donut'
>>> 
>>> # did I have breakfast or dinner?
>>> 'breakfast' in d
True
>>> 'dinner' in d
False
>>>

Basic Dict Code Examples - Meals

> Basic Dict Examples

These all use a "meals" dict which contains key/value pairs like 'lunch' -> 'hot dog'. The possible keys are 'breakfast', 'lunch', 'dinner', although a key may or not be present in the meals dict.

bad_start() Solution Code

def bad_start(meals):
    if 'breakfast' not in meals:
        return True
    if meals['breakfast'] == 'candy':
        return True
    return False
    # Can be written with "or" / short-circuiting avoids key-error
    # if 'breakfast' not in meals or meals['breakfast'] == 'candy':

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}.