Outline for May 18, 2009
Reading: §11.6
- Dictionary
- Collection of key-value pairs
- What a “mapping” is
- Mutable
- Creating dictionaries
- Using d = { }
- Using d = dict()
- Methods for dictionaries
- D.has_key(k): True if dictionary D has key k;
else False
- k in D: same as D.has_key(k)
- 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 (k, v) from D
- D.clear(): delete all entries in D
- Sorting the dictionary
- keylist.sort() sorts based on keys
- keylist.sort(cmpfun) sorts based on cmpfun
- Arguments to cmpfun are two (key, value) pairs
- Returns −1 if first > second; 0 if first = second;
1 if first < second
- Example: word frequency count
- Sorted alphabetically (see
wfc-1.py)
- Sorted by frequency (see
wfc-2.py)
- Sorted by frequency first, the alphabetically (see
wfc-3.py)