Outline for February 22, 2012
Reading:
§20
Dictionary
Collection of key-value pairs
What a “mapping” is
Mutable
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
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 [
wfc-2a.py
]
Sorted by frequency [
wfc-3.py
]
Sorted by frequency first, the alphabetically [
wfc-4.py
]
A PDF version is available here.
ECS 10, Basic Concepts of Computing
Winter Quarter 2012