Suppose we need to represent years and the total North American fossil fuel CO2 emissions for those years.
Question: How should we do this?
One option: years = [1799, 1800, 1801, 1802, 1902, 2002] # metric tons of carbon, thousands emissions = [1, 70, 74, 79, 82, 215630, 1733297]
We call these parallel lists: The years
list at position i
corresponds to the emissions
list at
position i
.
Question: How would operations on the data work? For example:
(a) to add an entry, eg, 1950, 734914?
We need to modify both lists.
We could append or keep both lists sorted (then must find the right spot
and insert there).
Either way, both lists must be kept in sync.
(b) to edit the emissions value for a particular year? Need to find the year in the years lists and modify the corresponding item in the emissions list.
In general, not terribly convenient.
Notice that the lists don't explicitly represent the associations like (1799, 1).
Option two: a list of lists. Better, but still somewhat of a pain to look up a year. Must search the list to find it.
There is a better way: a new type of object called "dictionary"
A dictionary keeps track of associations for you.
* you give it some info, and a value you want to store the info under.
* it stashes this pair for you.
* it makes lookup (and some other useful things) super easy.
# Braces indicate that you are defining a dictionary.
emissions_by_year = {1799: 1, 1800: 70, 1801: 74, 1802: 82, 1902: 215630, 2002: 1733297}
# Look up the emissions for the given year
print(emissions_by_year[1801])
# Add another year to the dictionary
emissions_by_year[1950] = 734914
print(emissions_by_year[1950])
Dictionary entries have two parts: a key and a value.
In our example, the key is the year and the value is the CO2 emissions.
Why is it called a key? Like a physical (or metaphorical) key, it provides a means of gaining access to something.
Keys don't have to be numbers. But they do have to be immutable objects.
d = {1:5, 3:45, 4:10}
d["abc"] = "Hello!"
d[ [1, 2, 3] ] = 77 # error
And the associated values can be anything: any type, and mutable or not.
d = {}
d[5] = ("Diane", "978-6024", "BA", 4236)
d["weird"] = ["my", "you", "walrus"]
d["nested"] = {"diane": 4236, "paul": 4238}
print(d)
Dictionaries themselves are mutable.
print(id(d))
d["me"] = "you" # Does NOT create a new dict. Changes this one.
print(id(d))
print(emissions_by_year)
# extend (add a new key and its value)
emissions_by_year[2009] = 1000000 # Wishful thinking
# update (change the value associated with a key)
emissions_by_year[2000] = 10 # Old value is tossed out
print(emissions_by_year) # Reports most recent values
# check for membership
1950 in emissions_by_year # A dict operator (not a function
# or method). This one is binary.
# remove a key-value pair
del emissions_by_year[1950] # A unary dict operator.
1950 in emissions_by_year # This is now false
# determine length (number of key-value pairs)
len(emissions_by_year)
# Iterating over the dictionary
for key in emissions_by_year:
print(key)
Why did the keys come out in an unexpected order??
Dictionaries are unordered.
The order that the keys are traversed (when you loop through) is arbitrary:
there is no guarantee that it will be in the order that they were added.
Silly analogy: A dict is like a filing assistant who is very efficient but keeps everything in a secret room. You have no idea how he organizes things, and you don't care -- as long as he can pull the file you need when you give him the key.
emissions_by_year.keys()
emissions_by_year.values()
items: the (key, value) pairs
emissions_by_year.items()
# this is a list of tuples
phone = {'555-7632': 'Paul', '555-9832': 'Andrew', '555-6677': 'Dan', '555-9823': 'Michael', '555-6342' : 'Cathy', '555-7343' : 'Diane'}
(a) Going through the keys
#The proper way:
for key in phone:
print(key)
# The is equivalent, but not considered good style:
for key in phone.keys():
print(key)
(b) Going through the key-value pairs:
# This gives you a series of tuples.
for item in phone.items():
print(item)
# You can pull the pieces of the tuple out as you go:
for (number, name) in phone.items():
print("Name:", name, "; Phone Number:", number)
Here's a dictionary mapping phone numbers to names.
Some people have more than one phone number, of course.
phone = {'555-7632': 'Paul', '555-9832': 'Andrew', '555-6677': 'Dan', '555-9823': 'Michael', '555-6342' : 'Cathy', '555-2222': 'Michael', '555-7343' : 'Diane'}
Suppose we want to create a list of all of Michael's phone numbers:
# Method 1
michael = []
for key in phone:
if phone[key] == 'Michael':
michael.append(key)
print(michael)
But what if I want to be able to do this for all people? Question: is there some object you could create to make this easy? Answer: A dictionary!
new_phone = {}
for (number, name) in phone.items():
if name in new_phone:
new_phone[name].append(number)
else:
new_phone[name] = [number]
new_phone
We call this an inverted dictionary.