Python Dictionaries
Dictionaries organize data using named values. Like lists, dictionaries hold multiple values. Each value is associated with a key.
Learning Objectives
You should be able to:
- Describe the differences between lists and dictionaries
- Create dictionaries
- Create, read, and delete dictionary values
Video Walkthrough
Use this video to follow along with the steps in this lab.
Dictionaries
Think about a regular dictionary that defines words. If you want to know the definition of a word, you find it in the dictionary, and once you've found the word, you read the definition. In Python, dictionaries work similarly. But the words are called keys, and the definitions are called values. In a Python dictionary, you look up a key and find its associated value. Dictionaries are kind of like lists, but instead of accessing elements by their index (an integer), you access elements by their key (a string).
In a terminal, run python to start an interactive Python shell.
python
Create Dictionaries
Create a small dictionary with the following code. Notice that the code spans multiple lines. Python won't run the code until you hit enter after the last curly brace. The key is always a string, and the value can be any data type. When creating a dictionary with multiple key-value pairs, separate each pair with a comma. A colon separates the keys from the values for each pair. The following 5 lines of code are treated as a single statement.
target = {
"name": "ACME Tech University",
"IP": "251.22.25.932",
"reason": "spite"
}
The target dictionary has 3 keys: name, IP, and reason. Each of those keys is associated with a value: ACME Tech University, 251.22.25.932, and spite. So if I look in the target dictionary for the key name, I will find the value ACME Tech University.
Use the print() function to display the target objects' keys and associated values. (And yes, I realize that "932" is not a valid number in an IP address--that is intentional.)
print(target)
The output should be:
{'name': 'ACME Tech University', 'IP': '251.22.25.932', 'reason': 'spite'}
You can add new keys and values just by accessing a non-existing key and assigning a value.
target['contact_name'] = "Alice"
print(target)
A fourth key and value should appear in the output.
A second way to create a Python dictionary is to create an empty dictionary variable and add key-value pairs in subsequent lines.
new_target = {}
new_target['name'] = "Other Tech University"
new_target['IP'] = "252.11.23.901"
new_target['reason'] = "love"
new_target['colors'] = ["Red", "Blue"]
new_target['priority'] = 3
print(new_target)
Access Dictionary Values
You can access dictionary values by key. You can use single quotes or double quotes for the key.
target['IP']
target['name']
target["reason"]
If you try to access a key that does not exist, or you use the wrong case for a key, you'll get an error.
target['NAME']
You will get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'NAME'
Update Dictionary Values
- Values of the dictionary can be updated by replacing the old value. The following code would update the value of the key
contact_nameto "Bob", or create a new value if the key did not already exist in the dictionary.
target['contact_name'] = "Bob"
print(target)
Remove Dictionary Key/Value Pairs
There are 2 ways to delete key/value pairs: pop() and del. The pop() function removes the key and value from the dictionary and returns the value. In the interpreter, the following code will display the value of the key "IP" and then remove it from the dictionary.
target.pop("IP")
print(target)
The del function can also be used to remove a key and value. Unlike pop(), del does not return the value. In the interpreter, the reason key and value will be removed, but the reason will not be displayed.
del target['reason']
print(target)
Summary
Dictionaries are commonly used in Python. Like lists, they are very flexible. Dictionary values can even be lists or dictionaries. Lists can have dictionary elements.
Challenge
- Create a dictionary object to hold information about a car.
- Think of at least 3 keys you will store and what values you will assign to those keys.
- After creating the dictionary object, add another key/value pair.
- Print the dictionary.
Reflection
- How are lists and dictionaries similar and different?
- What would be the best way to store the following data--lists or dictionaries? A combination of both?
- Names of babies born last year.
- Details about corporate earnings.
- Historical daily high temperatures.
Key Terms
- Data Type: Dictionary: A data structure in Python that stores data in key-value pairs. Dictionaries are mutable, meaning their contents can be changed after creation. They are defined using curly braces
{}, with each key-value pair separated by a colon:and pairs separated by commas. - Dictionary Key: An element used to identify and access a value in a dictionary. Keys must be unique and immutable, such as strings, numbers, or tuples. In the example dictionary {"name": "Alice", "age": 30, "city": "New York"}, "name", "age", and "city" are keys.
- Dictionary Value: The data associated with a key in a dictionary. Values can be of any data type and can be duplicated. In the example dictionary {"name": "Alice", "age": 30, "city": "New York"}, "Alice", 30, and "New York" are values.