Can't come up with a quote :) But dicts rules, yeah!
In Python, a dictionary
is a mutable, unordered collection of items. While other compound data types have only value as an element, a dictionary has a key-value pair.
Dictionaries are optimized to retrieve values when the key is known. Consider them as a mini database for your application.
Creating a dictionary is as simple as placing items inside curly braces {}
separated by commas or using dict()
function. An item has a key and a corresponding value that is expressed as a pair (key: value).
# Option 1: Explicitly define a ``dict`` object
my_dict = {
'name': 'John',
'age': 30,
'occupation': 'developer'
}
# Option 2: Pass keyword parameters
my_dict = dict(name='John', age=30, occupation='developer')
{'name': 'John', 'age': 30, 'occupation': 'developer'}
Or you can create an empty dictionary:
my_dict = {}
my_dict = dict()
print(my_dict)
{}
Accessing elements can be done by referring to its key name, enclosed in square brackets []
or using the .get()
method. Adding or modifying elements can be done by using the assignment operator (=
) along with the key in square brackets.
my_dict = {
'name': 'John',
'age': 30,
'occupation': 'developer'
}
# Access
print(my_dict['name'])
print(my_dict.get('age')) # 30
# Modify
my_dict['age'] = 31
# Add new key-value
my_dict['hobby'] = 'painting'
print(my_dict)
John
30
{'name': 'John', 'age': 31, 'occupation': 'developer', 'hobby': 'painting'}
The min()
and max()
functions can be used with dictionaries to find the minimum or maximum key or value.
Note: By default, these functions operate on the dictionary keys, but you can specify to operate on the values by using the key
parameter.
Finding minimum and maximum keys
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}
print(min(my_dict)) # Output: 'apple'
print(max(my_dict)) # Output: 'cherry'
apple
cherry
Finding minimum and maximum values, instead of keys.
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}
print(min(my_dict.values()))
print(max(my_dict.values()))
2
5
The sorted()
function returns a new sorted list from the items in any iterable. When used with dictionaries, you can sort by keys or values.
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}
sorted_keys = sorted(my_dict)
print(sorted_keys)
IMPORTANT: Output - is a list: ['apple', 'banana', 'cherry']
['apple', 'banana', 'cherry']
Method | Description | Example Code | Example Output |
---|---|---|---|
keys() |
Returns a view object containing the keys of the dictionary. | my_dict.keys() |
dict_keys(['name', 'age', 'occupation']) |
values() |
Returns a view object containing the values of the dictionary. | my_dict.values() |
dict_values(['John', 30, 'developer']) |
items() |
Returns a view object containing a tuple for each key-value pair. | my_dict.items() |
dict_items([('name', 'John'), ('age', 30), ('occupation', 'developer')]) |
update() |
Updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs. | my_dict.update({'hobby': 'painting'}) |
{'name': 'John', 'age': 30, 'occupation': 'developer', 'hobby': 'painting'} |
pop() |
Removes a specified key and returns the corresponding value. | removed_age = my_dict.pop('age') |
Removes 'age' from my_dict and returns 30 |
clear() |
Removes all items from the dictionary. | my_dict.clear() |
my_dict becomes {} |
Iterating over dictionaries can be done in several ways, such as by iterating over keys, values, or both.
Iterating over keys is the default behavior when iterating through a dictionary directly in a for
loop.
for key in my_dict:
print(f"Key: {key}")
Key: name
Key: age
Key: occupation
If you're only interested in values, use the .values()
method.
for value in my_dict.values():
print(f"Value: {value}")
Value: John
Value: 30
Value: developer
To get both keys and values simultaneously, use the .items()
method. This method is particularly useful when you need to work with both elements.
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
Key: name, Value: John
Key: age, Value: 30
Key: occupation, Value: developer
Dictionary comprehensions are not just for creating dictionaries; they can also be used to iterate over an existing dictionary.
Filter out items where the value is below a certain threshold. This is useful for data processing where you only want to keep items that meet certain criteria.
my_dict = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4}
filtered_dict = {key: value for key, value in my_dict.items() if value > 2}
print(filtered_dict)
Output:
{'cherry': 3, 'date': 4}
Inverting the keys and values of a dictionary can be useful in scenarios where you need to look up keys by their associated values.
my_dict = {'apple': 1, 'banana': 2, 'cherry':
3, 'date': 4}
inverted_dict = {value: key for key, value in my_dict.items()}
print(inverted_dict)
Output:
{1: 'apple', 2: 'banana', 3: 'cherry', 4: 'date'}
While enumerate()
is typically used with lists, it can also be applied to the .items()
of a dictionary to get both the index and the key-value pairs during iteration. Not sure, where it can be applicable, but just FYI that such option exists.
for index, (key, value) in enumerate(my_dict.items()):
print(f"Index: {index}, Key: {key}, Value: {value}")
Index: 0, Key: name, Value: John
Index: 1, Key: age, Value: 30
Index: 2, Key: occupation, Value: developer
Two dictionaries are considered equal if:
- They have the same set of keys.
- Corresponding keys have the same values.
Python checks each key-value pair during comparison, making it an efficient process.
dict_a = {'name': 'Alice', 'age': 25, 'city': 'Wonderland'}
dict_b = {'age': 25, 'city': 'Wonderland', 'name': 'Alice'}
print(dict_a == dict_b)
True
NOTE: Although dict_a
and dict_b
were defined in different orders, they are considered equal.
NOTE: Order does not matterm since Python 3.7, dictionaries maintain the insertion order of items. However, the order does not influence the outcome of equality comparisons.
The inequality operator returns True
if the dictionaries differ in at least one key or value.
dict_a = {'name': 'Alice', 'age': 25}
dict_b = {'name': 'Alice', 'age': 30}
# The values for the key 'age' are different, so dict_a and dict_b are not equal.
print(dict_a != dict_b)
True
Note: Deep comparison, the comparison is "deep" meaning nested dictionaries will also be compared accurately.
Nested dictionaries allow you to store and organize complex data structures.
To access elements within a nested dictionary, you chain square brackets []
or use the .get()
method for safer access.
family = {
'john': {'age': 30, 'job': 'developer'},
'jane': {'age': 28, 'job': 'designer'}
}
print(family['john']['job'])
developer
28
Specify the keys to the path of the item you want to modify.
# Modifying Jane's job
family['jane']['job'] = 'architect'
print(family['jane']['job'])
architect
Adding a new key-value pair to a nested dictionary might require ensuring that the parent dictionary exists.
This can be done using the .setdefault()
method or checking for the existence of the key.
# Adding a new key-value pair for John
family['john']['hobby'] = 'painting'
# Adding a new nested dictionary for a new family member
family['alice'] = {'age': 24, 'job': 'engineer'}
print(family)
{'john': {'age': 30, 'job': 'developer', 'hobby': 'painting'},
'jane': {'age': 28, 'job': 'designer'},
'alice': {'age': 24, 'job': 'engineer'}
}
To access keys and values, you might iterate over the outer dictionary and then over each nested dictionary.
for person, details in family.items():
print(f"Name: {person}")
for key, value in details.items():
print(f" {key.capitalize()}: {value}")
Name: john
Age: 30
Job: developer
Name: jane
Age: 28
Job: designer
To remove items either from default or a nested dictionary, use the del
statement or the .pop()
# Deleting a key-value pair
del family['john']['hobby']
# Removing an entire nested dictionary
removed_person = family.pop('alice', None)
print(f"Removed: {removed_person}")
{'john': {'age': 30, 'job': 'developer'}, 'jane': {'age': 28, 'job': 'designer'}}
Removed: {'age': 28, 'job': 'designer'}
What does the
pop()
method do in a Python dictionary?
A) Adds a new item to the dictionary
B) Returns the value of a key and removes the key-value pair from the dictionary
C) Sorts the dictionary
D) None of the above
How do you access the value associated with the key 'occupation' in the dictionary
my_dict
?
A) my_dict(occupation)
B) my_dict['occupation']
C) my_dict.get(occupation)
D) my_dict.get('occupation')
Which of the following statements about dictionaries in Python is true?
A) Dictionaries are ordered collections of items.
B) A dictionary's keys can be mutable types.
C) Dictionaries can contain mixed data types for keys and values.
D) A dictionary cannot contain another dictionary as a value.
How would you create a new dictionary that contains all the items from
dict1
anddict2
, where items indict2
overwrite items indict1
for matching keys?
A) dict1.update(dict2)
B) {**dict1, **dict2}
C) dict1 + dict2
D) dict2.update(dict1)
Which method would you use to safely retrieve a value from a dictionary, providing a default value if the key does not exist?
A) fetch()
B) get()
C) retrieve()
D) pull()
Objective: Create a simple movie recommendation system that suggests movies to users based on their preferences.
-
Movie Database: Create a dictionary named
movie_database
where keys are movie titles and values are lists containing the genre(s) of each movie. -
Recommendation Algorithm: Suggest a movie to a user based on their preferred genres and the movie database.
The format should be something like this:
movie_database = {
"Interstellar": ["Adventure", "Drama", "Sci-Fi"]
}
Objective: Create a flashcard quiz game that helps users learn and test their knowledge on various topics.
-
Data: Define a dictionary named
flashcards
where keys are questions and values are answers. -
Quiz: Implement a quiz functionality that presents users with a random flashcard question and prompts them to input their answer.
-
Repeat: Allow the user to continue the quiz until they decide to quit.
flashcards = {
"What is the chemical simbol for water?": "H2O",
}
# We haven't learnt modules yet, but you will need to figure out how to get the random question from ``flashcards``, I believe in you!