Exercise 39. Dictionaries, Oh Lovely Dictionaries

You are now going to learn about the Dictionary data structure in Python. A Dictionary (or dict) is a way to store data just like a list, but instead of using only numbers to get the data, you can use almost anything. This lets you treat a dict like it’s a database for storing and organizing data.

Let’s compare what dicts can do to what lists can do. You see, a list lets you do this:

Exercise 39 Python Session


>>> things = ['a', 'b', 'c', 'd']
>>> print(things[1])
b
>>> things[1] = 'z'
>>> print(things[1])
z
>>> things
['a', 'z', 'c', 'd']

You can use numbers to index into a list, meaning you can use numbers to find out what’s in lists. You should know this about lists by now, but make sure you understand that you can only use numbers to get items out of a list.

A dict lets you use anything, not just numbers. Yes, a dict associates one thing to another, no matter what it is. Take a look:

Exercise 39 Python Session


>>> stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
>>> print(stuff['name'])
Zed
>>> print(stuff['age'])
39
>>> print(stuff['height'])
74
>>> stuff['city'] = "SF"
>>> print(stuff['city'])
SF

You will see that instead of just numbers we’re using strings to say what we want from the stuff dictionary. We can also put new things into the dictionary with strings. It doesn’t have to be strings, though. We can also do this:

Exercise 39 Python Session


>>> stuff[1] = "Wow"
>>> stuff[2] = "Neato"
>>> print(stuff[1])
Wow
>>> print(stuff[2])
Neato

In this code I used numbers, and then you can see there are numbers and strings as keys in the dict when I print it. I could use anything. Well almost, but just pretend you can use anything for now.

Of course, a dictionary that you can only put things in is pretty stupid, so here’s how you delete things, with the del keyword:

Exercise 39 Python Session


>>> del stuff['city']
>>> del stuff[1]
>>> del stuff[2]
>>> stuff
{'name': 'Zed', 'age': 39, 'height': 74}

A Dictionary Example

We’ll now do an exercise that you must study very carefully. I want you to type this code in and try to understand what’s going on. Take note of when you put things in a dict, get them from a hash, and all the operations you use. Notice how this example is mapping states to their abbreviations and then the abbreviations to cities in the states. Remember, mapping (or associating) is the key concept in a dictionary.

ex39.py


 1    # create a mapping of state to abbreviation
 2    states = {
 3        'Oregon': 'OR',
 4        'Florida': 'FL',
 5        'California': 'CA',
 6        'New York': 'NY',
 7        'Michigan': 'MI'
 8    }
 9
10    # create a basic set of states and some cities in them
11    cities = {
12        'CA': 'San Francisco',
13        'MI': 'Detroit',
14        'FL': 'Jacksonville'
15    }
16
17    # add some more cities
18    cities['NY'] = 'New York'
19    cities['OR'] = 'Portland'
20
21    # print out some cities
22    print('-' * 10)
23    print("NY State has: ", cities['NY'])
24    print("OR State has: ", cities['OR'])
25
26    # print some states
27    print('-' * 10)
28    print("Michigan's abbreviation is: ", states['Michigan'])
29    print("Florida's abbreviation is: ", states['Florida'])
30
31    # do it by using the state then cities dict
32    print('-' * 10)
33    print("Michigan has: ", cities[states['Michigan']])
34    print("Florida has: ", cities[states['Florida']])
35
36    # print every state abbreviation
37    print('-' * 10)
38    for state, abbrev in list(states.items()):
39        print(f"{state} is abbreviated {abbrev}")
40
41    # print every city in state
42    print('-' * 10)
43    for abbrev, city in list(cities.items()):
44        print(f"{abbrev} has the city {city}")
45
46    # now do both at the same time
47    print('-' * 10)
48    for state, abbrev in list(states.items()):
49        print(f"{state} state is abbreviated {abbrev}")
50        print(f"and has city {cities[abbrev]}")
51
52    print('-' * 10)
53    # safely get a abbreviation by state that might not be there
54    state = states.get('Texas')
55
56    if not state:
57        print("Sorry, no Texas.")
58
59    # get a city with a default value
60    city = cities.get('TX', 'Does Not Exist')
61    print(f"The city for the state 'TX' is: {city}")

What You Should See

Exercise 39 Session


$ python3.6 ex39.py
----------
NY State has:  New York
OR State has:  Portland
----------
Michigan's abbreviation is:  MI
Florida's abbreviation is:  FL
----------
Michigan has:  Detroit
Florida has:  Jacksonville
----------
Oregon is abbreviated OR
Florida is abbreviated FL
California is abbreviated CA
New York is abbreviated NY
Michigan is abbreviated MI
----------
CA has the city San Francisco
MI has the city Detroit
FL has the city Jacksonville
NY has the city New York
OR has the city Portland
----------
Oregon state is abbreviated OR
and has city Portland
Florida state is abbreviated FL
and has city Jacksonville
California state is abbreviated CA
and has city San Francisco
New York state is abbreviated NY
and has city New York
Michigan state is abbreviated MI
and has city Detroit
----------
Sorry, no Texas.
The city for the state 'TX' is: Does Not Exist

What Dictionaries Can Do

A dictionary is another example of a data structure, and, like a list, it is one of the most commonly used data structures in programming. A dictionary is used to map or associate things you want to store to keys you need to get them. Again, programmers don’t use a term like “dictionary” for something that doesn’t work like an actual dictionary full of words, so let’s use that as our real world example.

Let’s say you want to find out what the word “honorificabilitudinitatibus” means. Today you would simply copy-paste that word into a search engine and then find out the answer, and we could say a search engine is like a really huge super complex version of the Oxford English Dictionary (OED). Before search engines what you would do is this:

1. Go to your library and get “the dictionary.” Let’s say it’s the OED.

2. You know “honorificabilitudinitatibus” starts with the letter “H” so you look on the side of the book for the little tab that has “H” on it.

3. Skim the pages until you are close to where “hon” starts.

4. Skim a few more pages until you find “honorificabilitudinitatibus” or hit the beginning of the “hp” words and realize this word isn’t in the OED.

5. Once you find the entry, you read the definition to figure out what it means.

This process is nearly exactly the way a dict works, and you are basically “mapping” the word “honorificabilitudinitatibus” to its definition. A dict in Python is just like a dictionary in the real world such as the OED.

Study Drills

1. Do this same kind of mapping with cities and states/regions in your country or some other country.

2. Find the Python documentation for dictionaries and try to do even more things to them.

3. Find out what you can’t do with dictionaries. A big one is that they do not have order, so try playing with that.

Common Student Questions

What is the difference between a list and a dictionary? A list is for an ordered list of items. A dictionary (or dict) is for matching some items (called “keys”) to other items (called “values”).

What would I use a dictionary for? When you have to take one value and “look up” another value. In fact, you could call dictionaries “look up tables.”

What would I use a list for? Use a list for any sequence of things that needs to be in order, and you only need to look them up by a numeric index.

What if I need a dictionary, but I need it to be in order? Take a look at the collections.OrderedDict data structure in Python. Search for it online to find the documentation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.56.45