Outline for October 28, 2024

Reading: text, §7
Due: Homework 2, due October 30, 2023


  1. Dictionary
    1. Collection of key-value pairs

  2. Creating dictionaries
    1. Using d = {}
    2. Using d = dict()

  3. Methods for dictionaries
    1. k in D: True if dictionary D has key k; else False
    2. D.keys(): list of keys in D
    3. D.values(): list of values in D
    4. D.items(): list of tuples (key, value) in D
    5. D.get(k, d): if key k in D, return associated value; else return d
    6. del D[k]: delete tuple with key k from D
    7. D.clear(): delete all entries in D

  4. Example: memos
    1. Remember how slowly the recursive Fibonacci number program rfib.py ran? Here is a faster recursive version that uses memos [rfibmemo.py]

  5. Sorting the dictionary
    1. sorted sorts based on keys

  6. Example: word frequency count
    1. Unsorted [wfc-1.py]
    2. Sorted alphabetically [wfc-2.py]
    3. Sorted alphabetically, but dictionary order (note key=str.lower() in sorted [wfc-3.py]
    4. Sorted by frequency (treat lambda x: x[1] as an idiom to reference the value of the dictionary entry, not the key—to go from highest to lowest, replace x[1] with -x[1]) [wfc-4.py]
    5. Sorted by frequency first, then alphabetically—note use of function alphafreq(x); you can use any function here, and the parameter is the item [wfc-5.py]

  7. Handling exceptions
    1. except [except0.py]
    2. except exceptcode [except1.py]
    3. else [except2.py]
    4. except exceptcode as msgvar [except3.py]
    5. finally [except4.py]
    6. Exceptions in a function: who handles them? [except5.py, except6.py]
    7. Using global variables as error flags [except7.py]
    8. raise exceptcode message [except8.py]

  8. Writing a program to play rock-paper-scissors: top-down design
    1. Problem statement and general algorithm idea
    2. Data representation and program structure [rps-1.py]
    3. Figure out who wins [rps-2.py]
    4. Get computer choice [rps-3.py]
    5. Get user input [rps-4.py]
    6. Make it user-friendly [rps-5.py]

UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: [email protected]
ECS 235A, Computer and Information Security
Version of October 27, 2024 at 9:37PM

You can also obtain a PDF version of this.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh