Home > Articles

Python 3 Dictionaries, Oh Lovely Dictionaries

  • Print
  • + Share This

Learn about the Dictionary data structure in Python.

Save 35% off the list price* of the related book or multi-format eBook (EPUB + MOBI + PDF) with discount code ARTICLE.
* See informit.com/terms

This chapter is from the book

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}")
  • + Share This
  • 🔖 Save To Your Account