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]
emissions = [1, 70, 74, 79, 82, 215630, 1733297] # metric tons of carbon, thousands
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 the expression (1799, 1)
does.
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) 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])
74 734914
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 (so, not lists, or dictionaries)
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)
{'weird': ['my', 'you', 'walrus'], 5: ('Diane', '978-6024', 'BA', 4236), 'nested': {'diane': 4236, 'paul': 4238}}
Dictionaries themselves are mutable -- you can modify their contents.
print(emissions_by_year)
# extend (add a new key and its value)
emissions_by_year[2009] = 1000000 # Wishful thinking
{2000: 10, 2002: 1733297, 1950: 734914, 1799: 1, 1800: 70, 1801: 74, 1802: 82, 2009: 1000000, 1902: 215630}
# 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
{2000: 10, 2002: 1733297, 1950: 734914, 1799: 1, 1800: 70, 1801: 74, 1802: 82, 2009: 1000000, 1902: 215630}
# check for membership
1950 in emissions_by_year # A dict operator (not a function
# or method). This one is binary.
True
# remove a key-value pair
del emissions_by_year[1950] # A unary dict operator.
1950 in emissions_by_year # This is now false
False
# determine length (number of key-value pairs)
len(emissions_by_year)
8
# Iterating over the dictionary
for key in emissions_by_year:
print(key)
2000 2002 1799 1800 1801 1802 2009 1902
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 they organize
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()
dict_keys([2000, 2002, 1799, 1800, 1801, 1802, 2009, 1902])
emissions_by_year.values()
dict_values([10, 1733297, 1, 70, 74, 82, 1000000, 215630])
items: the (key, value) pairs
emissions_by_year.items()
# this is a list of tuples
dict_items([(2000, 10), (2002, 1733297), (1799, 1), (1800, 70), (1801, 74), (1802, 82), (2009, 1000000), (1902, 215630)])
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)
555-9832 555-9823 555-7632 555-6342 555-7343 555-6677 555-9832 555-9823 555-7632 555-6342 555-7343 555-6677
(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)
('555-9832', 'Andrew') ('555-9823', 'Michael') ('555-7632', 'Paul') ('555-6342', 'Cathy') ('555-7343', 'Diane') ('555-6677', 'Dan') Name: Andrew ; Phone Number: 555-9832 Name: Michael ; Phone Number: 555-9823 Name: Paul ; Phone Number: 555-7632 Name: Cathy ; Phone Number: 555-6342 Name: Diane ; Phone Number: 555-7343 Name: Dan ; Phone Number: 555-6677
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)
['555-9823', '555-2222']
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
{'Andrew': ['555-9832'], 'Cathy': ['555-6342'], 'Dan': ['555-6677'], 'Diane': ['555-7343'], 'Michael': ['555-9823', '555-2222'], 'Paul': ['555-7632']}
We call this an inverted dictionary.