Dictionaries

Motivation

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"

Dictionary basics

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.
In [3]:
# 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.

In [4]:
d = {1:5, 3:45, 4:10}
d["abc"] = "Hello!"
d[ [1, 2, 3] ] = 77        # error
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-0dd3fde023f3> in <module>()
      1 d = {1:5, 3:45, 4:10}
      2 d["abc"] = "Hello!"
----> 3 d[ [1, 2, 3] ] = 77        # error

TypeError: unhashable type: 'list'

And the associated values can be anything: any type, and mutable or not.

In [8]:
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}}
In [ ]:
Dictionaries themselves are mutable.
In [9]:
print(id(d))
d["me"] = "you"  # Does NOT create a new dict.  Changes this one.
print(id(d))
4383712456
4383712456

Dictionary operations

In [10]:
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.
{2002: 1733297, 1950: 734914, 1799: 1, 1800: 70, 1801: 74, 1802: 82, 1902: 215630}
{2000: 10, 2002: 1733297, 1950: 734914, 1799: 1, 1800: 70, 1801: 74, 1802: 82, 2009: 1000000, 1902: 215630}
Out[10]:
True
In [11]:
# remove a key-value pair
del emissions_by_year[1950]         # A unary dict operator.
1950 in emissions_by_year           # This is now false
Out[11]:
False
In [12]:
# determine length (number of key-value pairs)
len(emissions_by_year)
Out[12]:
8
In [13]:
# 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 he organizes things, and you don't care -- as long as he can pull the file you need when you give him the key.

Dictionary methods

In [14]:
emissions_by_year.keys()
Out[14]:
dict_keys([2000, 2002, 1799, 1800, 1801, 1802, 2009, 1902])
In [15]:
emissions_by_year.values()
Out[15]:
dict_values([10, 1733297, 1, 70, 74, 82, 1000000, 215630])

items: the (key, value) pairs

In [16]:
emissions_by_year.items()
# this is a list of tuples
Out[16]:
dict_items([(2000, 10), (2002, 1733297), (1799, 1), (1800, 70), (1801, 74), (1802, 82), (2009, 1000000), (1902, 215630)])

Iterating through a dictionary

In [17]:
phone = {'555-7632': 'Paul', '555-9832': 'Andrew', '555-6677': 'Dan', '555-9823': 'Michael', '555-6342' : 'Cathy', '555-7343' : 'Diane'}

(a) Going through the keys

In [19]:
#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-7632
555-9832
555-7343
555-6677
555-9823
555-6342
555-7632
555-9832
555-7343
555-6677
555-9823
555-6342

(b) Going through the key-value pairs:

In [22]:
# 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-7632', 'Paul')
('555-9832', 'Andrew')
('555-7343', 'Diane')
('555-6677', 'Dan')
('555-9823', 'Michael')
('555-6342', 'Cathy')
Name: Paul ; Phone Number: 555-7632
Name: Andrew ; Phone Number: 555-9832
Name: Diane ; Phone Number: 555-7343
Name: Dan ; Phone Number: 555-6677
Name: Michael ; Phone Number: 555-9823
Name: Cathy ; Phone Number: 555-6342

Inverting a dictionary -- we did not cover this in level 1 lecture

Here's a dictionary mapping phone numbers to names.
Some people have more than one phone number, of course.

In [26]:
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:

In [27]:
# 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!

  • The old one takes us from numbers to names.
  • The new one will take us in the reverse direction, from names to #s
In [29]:
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
Out[29]:
{'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.