Dictionaries
- A list maps consecutive integers to data
['Bob', 'Dave', 'Tom']
maps 0 to Bob, 1 to Dave, and 2 to Tom.
- A dictionary can map keys of any type to a value.
- (Kind of like a mathematical function)
grades = {'John': 'A', 'Dave': 'B', 'George': 'C'}
- Can access much like a list:
grades['John']
- Dictionaries are mutable:
grades['Susan'] = 'A'
- Multiple ways to create a dictionary:
grades = {'John': 'A', 'Dave': 'B', 'George': 'C'}
grades = dict(John='A', Dave='B', George='C')
grades = dict([('John', 'A'), ('Dave', 'B'), ('George', 'C')])
- Like an array, key can be a variable:
student = input(); grades[student]
- Can delete a key with
del
- Use
in
to test for membershipif 'Scott' in grades
sales_tax = {
"Alabama": 0.04,
"Alaska": 0.0, # Alaska has no state-level sales tax
"Arizona": 0.056,
"Arkansas": 0.065,
"California": 0.0725,
"Colorado": 0.029,
"Connecticut": 0.0635,
"Delaware": 0.0, # Delaware has no state-level sales tax
"Florida": 0.06,
"Georgia": 0.04,
"Hawaii": 0.04,
"Idaho": 0.06,
'Michigan': 0.06,
'Indiana': 0.07,
'Illinois': 0.0625
}
Common methods
.clear
.get(key, default)
(usedefault
ifkey
isn’t in the dictionary).update(dict2)
merges two dictionaries.pop(key, default)
return and remove
Iteration
.items()
: (key, value) tuples.keys()
: return the keys.values()
: return the values- Order is not guaranteed!
Misc
-
Dictionaries can be nested
grades = { 'John Ponting': { 'Homeworks': [79, 80, 74], 'Midterm': 85, 'Final': 92 }, 'Jacques Kallis': { 'Homeworks': [90, 92, 65], 'Midterm': 87, 'Final': 75 }, 'Ricky Bobby': { 'Homeworks': [50, 52, 78], 'Midterm': 40, 'Final': 65 }, } print(grades['John Ponting']['Homeworks][1])