Home » Chapter 5 : Data Structures
Dictionaries
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 a dictionary method 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:
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:
Iterating (looping) through dictionaries differs from lists primarily in that accessing list items if through an index whereas accessing dictionary items is through keys and/or values.
Examples: The following examples demonstrate how to use a for loop to iterate through a dictionary using several approaches to display the keys and/or values in the dictionary. Pay particular attention to the syntax of each for loop signature in particular. Then review the Output and Code & Output Details below.
# Create single-entry dictionary
employee = {
"employee_id": 12345678,
"first_name": "Bob",
"last_name": "Smith",
"department": "Marketing",
"age": 25,
"hourly_rate": 23.50,
"insurance": True
}
# Print the keys in the dictionary.
for k in employee:
print(k)
print()
# Print the keys in the dictionary using the keys() method.
for k in employee.keys():
print(k)
print()
# Print the values in the dictionary.
for k in employee:
print(employee[k])
print()
# Print the values in the dictionary using the values() method.
for k in employee.values():
print(k)
print()
# Print both the keys and values using the items() method.
for k, v in employee.items():
print(k, v)
print()
Output:
employee_id
first_name
last_name
department
age
hourly_rate
insurance
employee_id
first_name
last_name
department
age
hourly_rate
insurance
12345678
Bob
Smith
Marketing
25
23.5
True
12345678
Bob
Smith
Marketing
25
23.5
True
employee_id 12345678
first_name Bob
last_name Smith
department Marketing
age 25
hourly_rate 23.5
insurance True
Code & Output Details:
Once we have created a dictionary, we have 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
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 using the update() method of the dictionary data structure 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'}
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
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}
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
Write a Python program that creates an empty contacts dictionary (first name and phone number), then adds one entry. Add two more entries using one statement. Loop through the dictionary and print all of the entries, first name and phone number, one entry per line with a tab escape sequence between each first name and phone number.
Marcus (801)444-5555
Sally (801)222-8888
Maria (385)333-1111
Write a Python program that prompts the user for an itinerary for a trip. Prompt them to enter the names of cities on the itinerary. Allow the user to enter any number of city names. Instruct them to press Enter by itself when they are finished. Add each user entry into a dictionary. When they are finished, loop through the dictionary and print their travel route. Here is an example of running the program:
Enter City Name: Denver
Enter City Name: Cleveland
Enter City Name: New York
Enter City Name: London
Enter City Name: Moscow
Enter City Name:
Travel Route: Denver to Cleveland to New York to London to Moscow
Write a Python program that translates words for fruit from English to Spanish. Here's a sample run of the program:
--------------------------------------------------------------------------------
Welcome to the English to Spanish Fruit Translator
--------------------------------------------------------------------------------
Enter name of a fruit in English (Press Enter alone to stop): watermelon
Watermelon in Spanish is la sandía
Enter name of a fruit in English (Press Enter alone to stop): cherry
Cherry in Spanish is la cereza
Enter name of a fruit in English (Press Enter alone to stop): moon
Sorry, moon is not in my translation dictionary.
Enter name of a fruit in English (Press Enter alone to stop): lemon
Lemon in Spanish is el limón
Enter name of a fruit in English (Press Enter alone to stop):
Thank you for using the English to Spanish Fruit Translator.
--------------------------------------------------------------------------------