Python Basic Dictionary Functions Cheat Sheet with Examples
1. get()
Method
The get()
method returns the value for the specified key if the key is in the dictionary. If the key is not found, it returns None
(or a specified default value).
Example:
student = {'name': 'Alice', 'age': 21, 'course': 'Physics'}
# Get existing key
print(student.get('name')) # Alice
# Get non-existing key returns None
print(student.get('grade')) # None
# Get with default value if key not found
print(student.get('grade', 'Not Assigned'))
Output:
Alice
None
Not Assigned
2. keys()
Method
The keys()
method returns a view object displaying all the keys in the dictionary.
Example:
student = {'name': 'Bob', 'age': 22, 'course': 'Math'}
keys = student.keys()
print(keys)
# Convert to list
print(list(keys))
Output:
dict_keys(['name', 'age', 'course'])
['name', 'age', 'course']
3. values()
Method
The values()
method returns a view object displaying all the values in the dictionary.
Example:
student = {'name': 'Charlie', 'age': 20, 'course': 'Biology'}
values = student.values()
print(values)
print(list(values))
Output:
dict_values(['Charlie', 20, 'Biology'])
['Charlie', 20, 'Biology']
4. items()
Method
The items()
method returns a view object of dictionary's key-value pairs as tuples.
Example:
student = {'name': 'Diana', 'age': 23, 'course': 'Chemistry'}
items = student.items()
print(items)
print(list(items))
# Loop through items
for key, value in student.items():
print(f"{key}: {value}")
Output:
dict_items([('name', 'Diana'), ('age', 23), ('course', 'Chemistry')])
[('name', 'Diana'), ('age', 23), ('course', 'Chemistry')]
name: Diana
age: 23
course: Chemistry
5. update()
Method
The update()
method updates the dictionary with key-value pairs from another dictionary or iterable of key-value pairs.
Example:
student = {'name': 'Eva', 'age': 24}
new_info = {'age': 25, 'course': 'Physics'}
# Before update
print(student)
# Update with new_info dictionary
student.update(new_info)
# After update
print(student)
# Update with iterable of tuples
student.update([('grade', 'A'), ('year', 3)])
print(student)
Output:
{'name': 'Eva', 'age': 24}
{'name': 'Eva', 'age': 25, 'course': 'Physics'}
{'name': 'Eva', 'age': 25, 'course': 'Physics', 'grade': 'A', 'year': 3}
6. pop()
Method
The pop()
method removes the specified key and returns its value. If the key is not found and default value is not provided, it raises KeyError
.
Example:
student = {'name': 'Frank', 'age': 26, 'course': 'Engineering'}
# Remove and get value of 'age'
age = student.pop('age')
print(f"Removed age: {age}")
print(student)
# Pop non-existing key with default value
grade = student.pop('grade', 'Not Assigned')
print(f"Grade: {grade}")
# Pop non-existing key without default causes error
# student.pop('grade') # KeyError
Output:
Removed age: 26
{'name': 'Frank', 'course': 'Engineering'}
Grade: Not Assigned
7. popitem()
Method
The popitem()
method removes and returns the last inserted key-value pair as a tuple. Raises KeyError
if the dictionary is empty.
Example:
student = {'name': 'Grace', 'age': 27, 'course': 'History'}
print("Before popitem:", student)
# Remove last item
item = student.popitem()
print("Popped item:", item)
print("After popitem:", student)
# Popitem until empty
student.popitem()
student.popitem()
# student.popitem() # KeyError if uncommented
Output:
Before popitem: {'name': 'Grace', 'age': 27, 'course': 'History'}
Popped item: ('course', 'History')
After popitem: {'name': 'Grace', 'age': 27}
8. clear()
Method
The clear()
method removes all items from the dictionary, making it empty.
Example:
student = {'name': 'Hank', 'age': 28, 'course': 'Philosophy'}
print("Before clear:", student)
student.clear()
print("After clear:", student)
Output:
Before clear: {'name': 'Hank', 'age': 28, 'course': 'Philosophy'}
After clear: {}
9. del
Keyword with Dictionary
The del
keyword can delete specific keys or the entire dictionary.
Example: Delete a key
student = {'name': 'Ivy', 'age': 29, 'course': 'Art'}
del student['age']
print(student)
Example: Delete entire dictionary
del student
# print(student) # NameError: name 'student' is not defined
Output:
{'name': 'Ivy', 'course': 'Art'}
10. copy()
Method
The copy()
method returns a shallow copy of the dictionary. Changes in the copy do not affect the original dictionary.
Example:
original = {'name': 'Jack', 'age': 30}
copy_dict = original.copy()
print("Original:", original)
print("Copy:", copy_dict)
# Change copy
copy_dict['age'] = 31
print("After change in copy:")
print("Original:", original)
print("Copy:", copy_dict)
Output:
Original: {'name': 'Jack', 'age': 30}
Copy: {'name': 'Jack', 'age': 30}
After change in copy:
Original: {'name': 'Jack', 'age': 30}
Copy: {'name': 'Jack', 'age': 31}
📚 Practice Questions:
📚 Related Topics:
- ➤ Python Arithmetic Operators
- ➤ Basic String Functions
- ➤ Advanced String Functions
- ➤ Basic List Functions
- ➤ Advanced List Functions : Part-1
- ➤ Advanced List Functions : Part-2
- ➤ Basic Tuple Functions
- ➤ Advanced Tuple Functions
- ➤ Basic Dictionary Functions
- ➤ Advanced Dictionary Functions
- ➤ Conditional Statements : if-elif-else
- ➤ Python 'for' Loop
- ➤ Python 'while' Loop
- ➤ Difference between 'for' loop and 'while' loop
- ➤ Introducing Python Functions
📌 Bookmark this blog or follow for updates!
👍 Liked this post? Share it with friends or leave a comment below!