Outline for November 30, 2012
Reading: § 18
Due Date Changed! Assignment Due: Friday, November 30, 2012 at 11:59 PM
- Dictionary
- Collection of key-value pairs
- Creating dictionaries
- Using d = {}
- Using d = dict()
- Methods for dictionaries
- k in D: True if dictionary D has key k; else False
- D.keys(): list of keys in D
- D.values(): list of values in D
- D.items(): list of tuples (key, value) in D
- D.get(k, d): if key k in D, return associated value; else return d
- del D[k]: delete tuple with key k from D
- D.clear(): delete all entries in D
- Example: memos
- Remember how slowly the recursive Fibonacci number program [rfib.py] ran? Here is a faster recursive Fibonacci [rfibmemo.py]
- Sorting the dictionary
- sorted sorts based on keys
- Example: word frequency count
- Unsorted [wfc-1.py]
- Sorted alphabetically [wfc-2.py]
- Sorted alphabetically, but dictionary order (note key=str.lower() in sorted [wfc-2a.py]
- 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-3.py]
- 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-4.py]
A PDF version is available here.
|
ECS 10, Basic Concepts of Computing
Fall Quarter 2012
|