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 is to use parallel lists, in which the years list at position i corresponds to the emissions list at position i:
years = [1799, 1800, 1801, 1802, 1902, 2002] # metric tons of carbon, thousands emissions = [1, 70, 74, 79, 82, 1733297]
Question: How would operations on the data work? For example:
(a) to add an entry, such as year `1950` and emissions `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?
We need to find the year in the years lists and modify the
corresponding item in the emissions list.
In general, storing the vlaues in this format is not terribly convenient.
Notice that the lists don't explicitly represent the associations like (1799, 1).
A second option is to use a list of lists. For example,
years_emissions = [[1799, 1], [1800, 70], [1801, 74], [1802, 79], [1902, 82], [2002, 1733297]]
Better, but still hard to look up a year, because we must search the list to find it.
There is a better way: a new type of object called a dictionary, which is represented by Python's type dict.
A dictionary keeps track of associations for you. Let's consider the emissions example:
# Braces indicate that you are defining a dictionary.
emissions_by_year = {1799: 1, 1800: 70, 1801: 74, 1802: 79, 1902: 82, 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; the list [1, 2, 3] cannot be a key because it is mutable.
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": 4234} # The values can even be dictionaries.
print(d)
Dictionaries themselves are mutable.
print(id(d))
d["me"] = "you" # Does NOT create a new dict. It 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[2009] = 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()
Method items produces the (key, value) pairs
emissions_by_year.items()
To work with the data returned by the methods described above, we typically convert it to type list. For example:
years = list(emissions_by_year.keys())
print(years)
doctor_to_patients that refers to an empty dictionary.'Dr. Ngo' with 1200 patients.'Dr. Singh' with 1400 patients.'Dr. Gray' with 1350 patinets.'Dr. Singh'.'Dr. Singh' to 1401.'Dr. Koch' is a key in the dictionary.'Dr. Ngo' as the key. 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)
# This 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)
The following dictionary has brand name drugs as keys and generic names as values:
branch_to_generic = {'lipitor': 'atorvastatin',
'zithromax': 'azithromycin',
'amoxcil': 'amoxicillin',
'singulair': 'montelukast',
'nexium': 'esomeprazole',
'plavix': 'clopidogrel',
'abilify': 'ARIPiprazole'}
Using the dictionary above and for loops, complete the following tasks:
'a'.'n'.Here's a dictionary mapping phone numbers to names.
Some people have more than one phone number, of course.
phone_to_person = {'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_to_person:
if phone_to_person[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_to_person.items():
if name in new_phone:
new_phone[name].append(number)
else:
new_phone[name] = [number]
new_phone
We call this an inverted dictionary.