Module #10

In this module you will learn about another data structure called dictionaries which can be used to store information using 'keys' rather than integer based indexes.


Dictionary Basics

A Dictionary is another helpful iterable data structure that is built-in to Python. In a natural language, a dictionary has a series of terms and each term has a definition. A Python dictionary isn't much different, but instead of "terms" we call them "keys" and instead of "definitions" we call them "values" or "data." In that sense a dictionary is a set of mappings from specific keys to specific values. The one difference between a natural language dictionary and a Python dictionary is that a Python dictionary is unordered. That means that unlike a list which has a set order, the order of items in a dictionary is undetermined.

Dictionaries can be incredibly useful if we want to store data and look that data up by name instead of using an index. Unlike the List sequence structure which uses an integer index to lookup values (and maintains the order of the list), a dictionary uses immutable objects (usually strings) called a key to find a specific value.

In other languages, dictionaries are sometimes called "hashmaps" or "associated arrays" since you can think of them as unordered arrays whose items are indexable using some associated data (the "key") instead of a number.

Creating a dictionary

You can create either empty dictionaries or dictionaries with items already in the dictionary. To create an empty dictionary we use the syntax { } or dict(). To create a new populated dictionary we can use the form { KEY_1: VALUE_1, KEY_2: VALUE_2, ..., KEY_N: VALUE_N }. Here are a few examples:

# Creating an empty dictionary
students = { }      # key - a student ID, value - name of the student

# Creating a dictionary with two entries (key-value pairs).
# In this case, the dictionary is of students, where the key is the
# student ID and the value is the name of the student
students = { "N12345678": "Andrew Case",
             "N87654321": "Bruce Wayne" }

Looking up items in a dictionary

You can access an element's value by simply using the syntax DICTIONARY_NAME[KEY]. So we can print() each student in our student dictionary defined above using:

print("Student: " + students["N12345678"])
print("Student: " + students["N87654321"])

Which results in the output:

Student: Andrew Case
Student: Bruce Wayne

Sample Program: In this sample program, we create a dictionary of technical words and allow the user to lookup the definitions for these words from the dictionary.



Working with dictionaries

Inserting/Replacing items in a dictionary

To insert or replace an item in the dictionary the form is DICTIONARY_NAME[KEY] = VALUE. For example:

students = dict()                        # Create an empty dictionary
students["N12345678"] = "Andrew Case"    # Add students to dictionary
students["N87654321"] = "Bruce Wayne"
students["N99999999"] = "Clark Kent"
If the item for that key doesn't exist, a new item will be created. If an item already exists for that key, the value will be overwritten with the new value.

Checking if an element exists

You can check if an element's value exists in a list using the form KEY in DICTIONARY_NAME like so:

if "N12345678" in students:
   print(students["N12345678"])
Output:
Andrew Case

Delete an item from a dictionary

Use the del keyword followed by the item to delete. The form is del DICTIONARY_NAME[KEY] like so:

del students["N12345678"]

Replace an item from a dictionary

Remember that the keys are immutable, so you can't change a key for an entry, but you can replace the value that is being referenced by a specific key. For example, let's say that "Bruce Wayne" wanted to officially change his name to "Batman." We could do so using the same method that we used to insert the original value:

students["N99999999"] = "Superman"

Iterating over Dictionaries

To iterate through each key and use that to pull each value we use the DICTIONARY_NAME.keys() function to get a sequence of keys for that dictionary. Here's an example of how we can iterate over each key:

for key in students.keys():
    print(key)
Output:
N99999999
N87654321

To iterate through each value we use DICTIONARY_NAME.values() function to get a sequence of all values in that dictionary. Here's an example:

for value in students.values():
    print(value)
Output:
Superman
Bruce Wayne

To iterate through each key-value pair we use the DICTIONARY_NAME.items() function to get both the key and value of each item in that dictionary. Here's an example:

for key, value in students.items():
    print(key, "->", value)
Ouptut:
N99999999 -> Superman
N87654321 -> Bruce Wayne

Differences between data structures

ListsDictionaries
Ordered? ordered by indexunordered
Lookup item using: numeric indexunique key
Duplicate values allowed:

When to use which data structure

To determine which data structure you should probably use, a basic approach is to follow these rules (there are times when these rules should be broken for performance reasons, but that is beyond the scope of this section):

  • If order matters: use a List
  • If you need to store/lookup values using a unique name/key: use a Dictionary

Sample Program: The following program repeatedly asks the user to enter a name. Once the user enters a blank name, it then prints the total number of times each name was entered.



Dictionary Methods

Like lists, dictionaries are objects which have methods that can run on any dictionary that has been created. Below are some of the most commonly used methods. You can get a list of all the dictionary methods by running help(dict) in a Python shell, or you can visit the Python API for a complete list.

Getting the number of items

You can use the same built-in len() function that works with lists to also get the length of a dictionary. In this case the syntax is len(DICTIONARY_NAME) which returns the number of items in the dictionary provided. Here is an example:

students = { "N12345678": "Andrew Case",
             "N87654321": "Bruce Wayne" }
print("Number of items:", len(students))
Output:
Number of items: 2

Getting a value

In addition to the syntax DICTIONARY_NAME[KEY] to get a value (which could error if the key doesn't exist), there is a method you can use to avoid getting a possible KeyError. DICTIONARY_NAME.get(key[, default]) returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None. Here is an example:

students = { "N12345678": "Andrew Case",
             "N87654321": "Bruce Wayne" }
print(students.get("N12345678"))
print(students.get("N11111111"))
Output:
Andrew Case
None

Getting all keys

Sometimes you may want to lookup what keys are stored in the dictionary. To do that you'll use the DICTIONARY_NAME.keys() method. This method will return a list data structure where each item in the list is one of the keys from the dictionary. Here's an example:

students = { "N12345678": "Andrew Case",
             "N87654321": "Bruce Wayne" }

# Get all the studentIDs (the keys)
student_IDs = students.keys()

# Print all the studentIDs
for student_ID in student_IDs:
    print("ID:", student_ID)
Output:
ID: N87654321
ID: N12345678

Note: Since a dictionary is unordred, the order of the returned items is arbitrary.

Getting all values

Other times, you may just want to get a list of all the values stored in a dictionary. To do that you'll use the DICTIONARY_NAME.values() method:

students = { "N12345678": "Andrew Case",
             "N87654321": "Bruce Wayne" }

# Get all student names (values in the dictionary)
student_names = students.values()

# Print all the students one at a time
for student in student_names:
    print("Student:", student)
Output:
Student: Bruce Wayne
Student: Andrew Case

Removing a specific item

Often we may want to remove an item from the dictionary to do some sort of processing on it. Instead of getting the item and then deleting it, we can do so with the pop() method. DICTIONARY_NAME.pop(key[, default]) returns the value for key and removes the item if it exists, otherwise default is returned. If default is not specified and key is not in the dictionary, a KeyError is raised. Here is an example:

students = { "N12345678": "Andrew Case",
             "N87654321": "Bruce Wayne" }

# Remove myself and print the results
student = students.pop("N12345678")
print("Student =", student)

# Print remaining students in the dictionary
print("Students =", students)
Output:
Student = Andrew Case
Students = {'N87654321': 'Bruce Wayne'}

Removing an unspecified item

Often we may not care which item to pull out of a dictionary. We can do this using the DICTIONARY_NAME.popitem() method which removes and returns an arbitrary (key, value) pair from the dictionary. This can be useful if you want to remove and process items at the same time. If the dictionary is empty, calling popitem() raises a KeyError. Here's an example:

students = { "N12345678": "Andrew Case",
             "N87654321": "Bruce Wayne" }

# Remove and print one item
student = students.popitem()
print(student)

# Remove and print another item
student_id, student_name = students.popitem()
print("Student ID:", student_id)
print("Student:", student_name)
Output:
('N87654321', 'Bruce Wayne')
Student ID: N12345678
Student: Andrew Case

Programming Challenge: Below is unfinished code for a program that presents an interface for a technology related natural language dictionary. It will present a menu to the user and the ability to add, list, lookup, and delete terms from the dictionary. Compete the TODO sections so that these functions provide the proper functionality.

Note: The web-based coding environment does not provide real-time output. To work on this problem it is highly advised that you launch IDLE on your own computer and run the code locally.

Click the "Run" button to check your work, and click here to download the solution.



Quiz

Now that you've completed this module, please visit our NYU Classes site and take the corresponding quiz for this module. These quizzes are worth 5% of your total grade and are a great way to test your Python skills! You may also use the following scratch space to test out any code you want.

Feedback

Tell us what you thought about this module (it's anonymous).
How helpful did you find this module on a scale of 1-5:
Very unhappy face
Unhappy face
Neutral face
Happy face
Very happy face
Which resource(s) in this module did you find the most helpful (check all that apply):

Copyright 2014-2018