Table of Contents » Chapter 2 : Data (Input) : Data Structures : Dictionaries
Dictionaries
Contents
Overview
Dictionaries in Python are collections of data values stored as key:value pairs. Dictionaries in Python are not indexed like lists; rather they are indexed by the keys of the key:value pairs. Keys in dictionaries must be unique, dictionaries cannot contain duplicate keys, similar to primary keys in databases.
| Dictionary Attribute | Description |
|---|---|
| Heterogeneous | Dictionaries are heterogeneous, that is, they can store different values of different data types at the same time. |
| Ordered | The items in a dictionary are in order and remain that way unless we use Dictionary Methods ↗ to alter that order. |
| Mutability | The items in a dictionary are mutable (changeable), that is, they can be changed, added, and removed after they have been added to the dictionary. |
| Duplicates | Dictionaries cannot have duplicate keys, however values within the dictionary can be duplicated, for example, key1:4444, key1,4444 are not allowed, but key1:4444, key2:4444 are allowed. |
| Indexing | Dictionaries are not indexed like lists, rather they are indexed based on their keys since keys are required to be unique in dictionaries. |
| Have Methods | Because dictionaries are objects, they have methods ↗. You can find a full list of dictionary methods here ↗. |
| Can Be Nested | Dictionaries can contain dictionaries, that is, any dictionary element can contain a dictionary. |
Creating a dictionary requires a variable, the assignment operator (=), and a set of key:value pairs enclosed in curly braces { }. Here is the general form of creating a list:
dictionary_variable = {key1:value, key2:value, ... keyN:value}
Here are several code examples:
# Empty dictionary
d = {}
# Dictionary
simple_d = {"key1": 111111}
# Dictionary
employee = {
"employee_id": 12345678,
"first_name": "Bob",
"last_name": "Smith",
"department": "Marketing",
"age": 25,
"hourly_rate": 23.50,
"insurance": True
}
# Nested Dictionary
employees = {
"e1": {
"employee_id": 23456789,
"first_name": "Mateo",
"last_name": "Garcia",
"department": "CEO",
"age": 53,
"hourly_rate": 144.33,
"insurance": True
},
"e2": {
"employee_id": 34567890,
"first_name": "Sally",
"last_name": "Jones",
"department": "IT",
"age": 41,
"hourly_rate": 36.00,
"insurance": True
}
}
Code Details:
- Code Line 2: Creating an empty dictionary called d.
- Code Line 5: Creating a dictionary called simple_d with one key:value pair. The key in this example is key1 and the value is 111111.
- Code Lines 8 thru 16: Creates a dictionary called employee with seven key:value pairs, one per line in the code. So, for example, the first pair is key employee_id and value 12345678.
- Code Lines 19 thru 38: Creates a dictionary called employees with two nested dictionaries in it, one called e1 and the second called e2.
Let's expand on the code above for creating the dictionaries to demonstrate how to access items in those dictionaries:
# Empty dictionary
d = {}
print(d)
# Simple Dictionary
simple_d = {"key1": 111111}
print(simple_d)
print("Key1: " + str(simple_d["key1"]))
print()
# Single Dictionary
employee = {
"employee_id": 12345678,
"first_name": "Bob",
"last_name": "Smith",
"department": "Marketing",
"age": 25,
"hourly_rate": 23.50,
"insurance": True
}
print(employee)
print("Employee Key: " + str(employee["employee_id"]))
print("Employee Age: " + str(employee.get("age")))
print()
# Nested Dictionary
employees = {
"e1": {
"employee_id": 23456789,
"first_name": "Mateo",
"last_name": "Garcia",
"department": "CEO",
"age": 53,
"hourly_rate": 144.33,
"insurance": True
},
"e2": {
"employee_id": 34567890,
"first_name": "Sally",
"last_name": "Jones",
"department": "IT",
"age": 41,
"hourly_rate": 36.00,
"insurance": True
}
}
print(employees)
print("Employee 1 ID: " + str(employees["e1"]["employee_id"]))
print("Employee 2 ID: " + str(employees["e2"]["employee_id"]))
Output:
Empty Dictionary: {}
Simple Dictionary: {'key1': 111111}
Key1: 111111
Employee Dictionary: {'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
Employee Key: 12345678
Employees Dictionary: {'e1': {'employee_id': 23456789, 'first_name': 'Mateo', 'last_name': 'Garcia', 'department': 'CEO', 'age': 53, 'hourly_rate': 144.33, 'insurance': True}, 'e2': {'employee_id': 34567890, 'first_name': 'Sally', 'last_name': 'Jones', 'department': 'IT', 'age': 41, 'hourly_rate': 36.0, 'insurance': True}}
Employee 1 ID: 23456789
Employee 2 ID: 34567890
Code & Output Details:
- Code Line 2: Creating an empty dictionary called d.
- Output Line 1: Shows the empty dictionary { }.
- Code Line 6: Creating a dictionary called simple_d with one key:value pair. The key in this example is key1 and the value is 111111.
- Code Line 7: Prints the full simple_d dictionary, which appears on Output Line 3.
- Code Line 8: Demonstrates how to access a value based on its key, which is displayed on Output Line 4. The syntax simple_d["key1"] means to access the dictionary and, using the key, in this case, key1, return the value associated with that key, which is 111111.
- Code Lines 12 thru 20: Creates a dictionary called employee with seven key:value pairs, one per line in the code. So, for example, the first pair is key employee_id and value 12345678.
- Code Line 21: Prints the full employee dictionary, which appears on Output Line 6.
- Code Line 22: Demonstrates another example of accessing a dictionary value using the key associated with that value. In this example, employee["employee_id"] returns the value for the key:value pair of employee_id: 12345678, which is displayed on Output Line 7.
- Code Line 23: Demonstrates the use of the get() dictionary data structure to access a value of the dictionary based on the specified key.
- Code Lines 27 thru 46: Creates a dictionary called employees with two nested dictionaries in it, one called e1 and the second called e2.
- Code Line 47: Prints the full employees dictionary, which is a nested dictionary, which appears on Output Line 9.
- Code Line 48: Demonstrates an example of accessing a nested dictionary value using the key associated with that value. In this example, employees["e1"]["employee_id"]) returns the value for the key:value pair of the nested dictionary e1's employee_id key, the result is displayed on Output Line 10.
- Code Line 49: Demonstrates an example of accessing a nested dictionary value using the key associated with that value. In this example, employees["e2"]["employee_id"]) returns the value for the key:value pair of the nested dictionary e2's employee_id key, the result is displayed on Output Line 11.
Once we have created a dictionary, we can use several approaches we can use to update (change) existing values in the dictionary. We can update values directly based on existing keys or we can use the .update() method of the dictionary data structure to update values based on their keys as well. Here are some examples with sample Output and Code & Output Details below.
Examples:
employee = {
"employee_id": 12345678,
"first_name": "Bob",
"last_name": "Smith",
"department": "Marketing",
"age": 25,
"hourly_rate": 23.50,
"insurance": True
}
print(employee)
employee["department"] = "Sales"
print(employee)
print("New Department: " + employee["department"])
employee.update({"hourly_rate": 29.00})
print(employee)
print("New Hourly Rate: " + str(employee["hourly_rate"]))
Output:
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Sales', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
New Department: Sales
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Sales', 'age': 25, 'hourly_rate': 29.0, 'insurance': True}
New Hourly Rate: 29.0
Code & Output Details:
- Code Lines 1 thru 9: Creates a dictionary called employee with 7 key:value pairs.
- Code Line 10: Prints the entire dictionary, shown on Output Line 1.
- Code Line 11: Updates the key "department" directly by addressing the employee key and a new value, separated by the assignment operator (=).
- Code Line 12: Prints the entire dictionary again for comparison, shown on Output Line 2.
- Code Line 13: Prints a formatted output statement and the employee department key value, shown on Output Line 3.
- Code Line 14: Updates the key "hourly_rate" using the update() method of the dictionary data structure. Notice the syntax on this line, inside the update method's parenthesis, is the key and new value inside of { } braces.
- Code Line 15: Prints the entire dictionary again for comparison, shown on Output Line 4.
- Code Line 16: Prints a formatted output statement and the employee's hourly rate key value, shown on Output Line 5.
We can also add new key:value pairs to a dictionary, which changes its size and again is possible because dictionaries are mutable (changeable). We can add pairs directly or use the dictionary data structure's update() method as demonstrated below:.
Examples:
employee = {
"employee_id": 12345678,
"first_name": "Bob",
"last_name": "Smith",
"department": "Marketing",
"age": 25,
"hourly_rate": 23.50,
"insurance": True
}
print(employee)
employee["years_service"] = 14
print(employee)
employee["office_location"] = "Building 1"
print(employee)
employee.update({"work_schedule": "Day Shift"})
print(employee)
Output:
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1'}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1', 'work_schedule': 'Day Shift'}
Code & Output Details:
- Code Lines 1 thru 9: Creates a dictionary called employee and adds the first set of key/value pairs to it.
- Code Line 10: Prints the dictionary showing the results.
- Code Line 11: Adds a new dictionary key:value pair. As long as the specified key does not already exist in the dictionary, it is added and assigned the value on the right side of the assignment operator (=).
- Code Line 12: Prints the dictionary showing the results of adding the new pair.
- Code Line 13: Adds another key/value pair to the dictionary.
- Code Line 14: Prints the dictionary showing the results.
- Code Line 15: Uses the dictionary update() method to add another key:value pair.
- Code Line 16: Prints the dictionary showing the results.
We can remove (delete) key:value pairs from a dictionary in several different ways, as demonstrated below:
Examples:
employee = {
"employee_id": 12345678,
"first_name": "Bob",
"last_name": "Smith",
"department": "Marketing",
"age": 25,
"hourly_rate": 23.50,
"insurance": True
}
employee.pop("department")
print(employee)
employee.popitem()
print(employee)
del employee["age"]
print(employee)
employee.clear()
print(employee)
del employee
print(employee)
Output:
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1'}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1', 'work_schedule': 'Day Shift'}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1', 'work_schedule': 'Day Shift'}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1'}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'hourly_rate': 23.5, 'insurance': True, 'years_service': 14, 'office_location': 'Building 1'}
{}
Traceback (most recent call last):
File "C:\Users\jg\PycharmProjects\Computing1010\Lecture.py", line 28, in
print(employee)
NameError: name 'employee' is not defined
Code & Output Details:
- Code Lines 1 thru 9: Creates a dictionary called employee.
- Code Lines 10: Uses the pop method of the dictionary to remove (pop) the key/value pair specified by the key "department".
- Code Line 11: Prints the dictionary to show the results.
- Code Line 12: Uses the popitem() method of the dictionary data structure to remove the last key/value pair in the dictionary.
- Code Line 13: Prints the dictionary to show the results.
- Code Line 14: Uses the Python built-in function del to delete a dictionary item based on the specified key ("age").
- Code Line 15: Prints the dictionary to show the results.
- Code Line 16: Uses the clear() method of the dictionary data structure to clear (remove) all items from the dictionary. The clear() method does not delete the dictionary data structure itself though.
- Code Line 17: Prints the dictionary to show the results.
- Code Line 14: Uses the Python built-in function del to delete the entire employee dictionary.
- Code Line 15: This line causes an error because it tries to print the employee dictionary, however, it was deleted in Code Line 18.
The dictionary data structure has a few additional methods: fromkeys(), copy(), and setdefault().
Examples:
# Example of fromkeys() method:
# Creates a dictionary based on a list of keys,
# with an optional default value for each key
key_list = ["key1", "key2", "key3"]
default_value = 0
new_dictionary = dict.fromkeys(key_list, default_value)
print(new_dictionary)
print()
# We'll use this employee dictionary for the next
# two method examples...
employee = {
"employee_id": 12345678,
"first_name": "Bob",
"last_name": "Smith",
"department": "Marketing",
"age": 25,
"hourly_rate": 23.50,
"insurance": True
}
print(employee)
# Example of copy() method:
# Copies a dictionary
copy_of_employee = employee.copy()
print(copy_of_employee)
print()
# Example of setdefault() method:
# Returns a value based on a specified key, if the
# key does not exist, the key is created and its
# value set to the specified value.
sal = employee.setdefault("hourly_rate", 0)
print(sal)
sal = employee.setdefault("annual_salary", 48880)
print(sal)
print(employee)
Output:
{'key1': 0, 'key2': 0, 'key3': 0}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
23.5
48880
{'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True, 'annual_salary': 48880}
Code & Output Details:
- Code Line 4: Creates a list of key names we will use to create a new dictionary.
- Code Line 5: Creates a variable that we'll use for a default value for the new dictionary.
- Code Line 6: Sets a new variable equal to the result of the fromkeys() method, based on the list of keys and the default value.
- Code Line 7: Prints the new dictionary.
- Code Lines 12 thru 20: Defines a dictionary called employee that will be used for the next two method examples.
- Code Line 25: Sets a new variable to the employee dictionary copy() method.
- Code Line 26: Prints the new copied dictionary.
- Code Line 33: Uses the setdefault() method to acquire the value of the hourly_rate key store that value in the variable sal. In this case, the hourly_rate key exists, so its value is stored in the variable.
- Code Line 35: Uses the setdefault() method to attempt to acquire the value of the key annual_salary, however since that key does not exist, the setdefault() method creates is in the dictionary and defaults the value to the specified value of 0.
In addition to the Dictionary Methods ↗ demonstrated above, there are several Python built-in functions we can use with dictionaries as well: len(), str() and type(). Also the in and == operators are useful with dictionaries as well.
Examples:
employee = {
"employee_id": 12345678,
"first_name": "Bob",
"last_name": "Smith",
"department": "Marketing",
"age": 25,
"hourly_rate": 23.50,
"insurance": True
}
print("Length of employee dictionary: " + str(len(employee)))
print("Employee dictionary converted to string: " + str(employee))
print(type(employee))
if "department" in employee:
print("Department: " + employee["department"])
d1 = {1, 2, 3, 4, 5}
d2 = {1, 2, 3, 4, 5}
d3 = {5, 4, 3, 2, 1}
d4 = {1, 2, 3, 4, 5, 6}
d5 = {"A", "B", "C"}
print(d1 == d2)
print(d1 == d3)
print(d1 == d4)
print(d1 == d5)
Output:
Length of employee dictionary: 7
Employee dictionary converted to string: {'employee_id': 12345678, 'first_name': 'Bob', 'last_name': 'Smith', 'department': 'Marketing', 'age': 25, 'hourly_rate': 23.5, 'insurance': True}
Department: Marketing
True
True
False
False
Code & Output Details:
- Code Lines 1 thru 9: Creates a dictionary called employee.
- Code Line 10: Prints the length of the dictionary using the len() function.
- Code Line 11: Prints the dictionary after it has been converted to a string version, using the str() functions, where all values are strings.
- Code Line 12: Uses the type() function to print the data type of the dictionary.
- Code Line 13: Uses the in operator to check if a key is in the employee dictionary.
- Code Lines 15 thru 19: Creates several dictionaries for comparison.
- Code Lines 20 thru 23: Use the == operator to compare dictionaries.
Problem 1
Write a Python program that creates a simple one-entry dictionary with a single key:value pair where the key is a customer ID and the value is an integer value like 1234. Then use a print statement to print the following:
Customer ID: 1234
Problem 2
Write a Python program that creates a multi-entry dictionary with a four key:value pairs of the following keys:
customer_id
first_name
last_name
email
You can include any data values for those four keys that you like. Then use a single print statement to print the values of the four dictionary entries. The output should look something like this:
--------------------
Customer
--------------------
Customer ID: 1234
Name: Bob Smith
Email: bob@abc.com
--------------------
Problem 3
Copy your code from Problem 2 above that will produce the same output, and then add code to change the value of the customer's email address. And then, duplicate your output code to display the before and after the email address value:
Note: We will see a more efficient way to repeat blocks of code in Chapter 3.