= {'DE': 1787, 'MD': 1788, 'VA': 1788} years
Week 9: Dictionaries
Reading: Think Python Chapter 11
(You can skip 11.4 - Reverse Lookup)
Notes
Keys and Values
So far, we have seen lists and strings, ordered collections that are indexed based on the position of their content.
Dictionaries, or dicts, are unordered, and consist of pairs of keys and values. They are created with curly braces {
and }
but indexed with square brackets [
and ]
.
'DE'] years[
1787
Note how the keys and values are separated by a colon :
.
New elements can be added to a dictionary via indexing and assignment:
'NC'] = 1788 years[
years
{'DE': 1787, 'MD': 1788, 'VA': 1788, 'NC': 1788}
Dicts are mutable in the same way that lists are.
'NC'] += 1 years[
years
{'DE': 1787, 'MD': 1788, 'VA': 1788, 'NC': 1789}
Dictionaries are very useful for counting problems. Here’s an example.
This program counts the occurrences of each letter in a string:
You can check if some value is a dictionary key with the in
keyword:
= {'DE': 1787, 'MD': 1788, 'VA': 1788} years
'DE' in years
True
'NJ' in years
False
You can extract the keys and values of a dict with the built-in methods <dict>.keys()
and <dict>.values()
:
years.keys()
dict_keys(['DE', 'MD', 'VA'])
years.values()
dict_values([1787, 1788, 1788])
These output special dict_keys
and dict_values
objects. You can covert these to lists with the list
function:
list(years.values())
[1787, 1788, 1788]
Calling len
on a dict will give you the number of key-value pairs:
len(years)
3
Any immutable value, such as ints, floats, and strings, can be a key.
Mutable data types such as lists and other dicts cannot be keys.
Iterating
Looping through a dict with a while
loop is cumbersome; using a for
loop, it is straightforward. Content iteration over a dict iterates over the keys:
Global Variables
- You have seen how variables created inside of functions only exist inside of functions
- We have passed variables in to functions as arguments
- Functions can also read variables from outside of functions
- Variables outside of functions are called “global” variables
- Functions cannot assign to global variables
It is possible to allow a function to assign to a global variable by using the keyword global
:
Without Line 2, this program would result in an error.
In practice, you should not reference global variables from functions. Pass arguments in and use return values.
Practice
Practice Problem 9.1
Practice Problem 9.2
Practice Problem 9.3
Practice Problem 9.4
Homework
Homework problems should always be your individual work. Please review the collaboration policy and ask the course staff if you have questions.
Double check your file names and return values. These need to be exact matches for you to get credit.