Dictionary Methods
Part of the Logic & Flow section of Coddy's Python journey — lesson 12 of 78.
Dictionaries, just like lists, come equipped with a variety of built-in methods to perform common operations. These methods can help you manipulate dictionaries more efficiently. Let's explore some of the key methods:
keys(): Returns a view object that displays a list of all the keys in the dictionary.
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
keys = my_dict.keys()
print(keys)
# Output: dict_keys(['name', 'age', 'city'])values(): Returns a view object that displays a list of all the values in the dictionary.
values = my_dict.values()
print(values)
# Output: dict_values(['Alice', 30, 'New York'])items(): Returns a view object that displays a list of a dictionary's key-value tuple pairs.
items = my_dict.items()
print(items)
# Output: dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])get(key, default): Returns the value for the specified key. If the key is not found, it returns the default value (or None if no default is specified).
age = my_dict.get('age')
print(age)
# Output: 30
country = my_dict.get('country', 'USA')
print(country)
# Output: USApop(key): Removes the element with the specified key and returns its value.
city = my_dict.pop('city')
print(city)
# Output: 'New York'
print(my_dict)
# Output: {'name': 'Alice', 'age': 30}Challenge
EasyIn this challenge, you'll work with a dictionary of student grades to practice essential dictionary operations.
Follow these steps in order and use the exact print statements shown:
- Create a dictionary named
gradeswith these initial key-value pairs:- "Alice": 85
- "Bob": 90
- "Charlie": 78
- Print all student names and grades using these exact statements:
print("Students:", grades.keys())print("Grades:", grades.values())
- Add a new student "Diana" with a grade of 92.
- Use the
get()method to retrieve Bob's grade, store it in a variable calledbobs_grade, and print it using:print("Bob's grade:", bobs_grade)
- Remove "Charlie" from the dictionary using the
pop()method and then print the updated dictionary using:print("Updated grades:", grades)
Important: Follow the exact sequence and use the exact print statements shown above to match the expected output.
Expected Output:
Students: dict_keys(['Alice', 'Bob', 'Charlie'])
Grades: dict_values([85, 90, 78])
Bob's grade: 90
Updated grades: {'Alice': 85, 'Bob': 90, 'Diana': 92}Cheat sheet
Dictionary methods for common operations:
keys(): Returns all dictionary keys
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
keys = my_dict.keys()
print(keys)
# Output: dict_keys(['name', 'age', 'city'])values(): Returns all dictionary values
values = my_dict.values()
print(values)
# Output: dict_values(['Alice', 30, 'New York'])items(): Returns key-value pairs as tuples
items = my_dict.items()
print(items)
# Output: dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])get(key, default): Returns value for key, or default if key not found
age = my_dict.get('age')
print(age)
# Output: 30
country = my_dict.get('country', 'USA')
print(country)
# Output: USApop(key): Removes and returns value for specified key
city = my_dict.pop('city')
print(city)
# Output: 'New York'
print(my_dict)
# Output: {'name': 'Alice', 'age': 30}Try it yourself
# Step 1: Create the Grades Dictionary
grades = {
# Add initial student grades here
}
# Step 2: Access All Keys and Values
# Print all students and grades
# Step 3: Add a New Student
# Add Diana with a grade of 92
# Step 4: Retrieve a Student's Grade
# Get Bob's grade using get() method
# Step 5: Remove a Student
# Remove Charlie using pop() method
# Print the updated dictionaryThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter