Learning Objectives
- Understand how to Create, Read, Update & Delete elements in a dictionary using various Python methods & special syntax
Working with Dictionaries (CRUD)
In order to build more complex applications, we need to understand how to perform the 4 main operations of handling data:
- Create
- Read
- Update
- Delete
Creating a Dictionary
A dictionary in Python is a collection of key-value pairs where each key is unique.
Keys and their associated values are wrapped in curly braces and separated by commas.
student_info = {'name': 'John',
'age': 16,
'grade': '10th'}
Reading a Dictionary
We can access the value associated with a specific key in a dictionary by using the .get()
method.
The .get()
method takes in one argument, which is the name of the key.
student_info = {'name': 'John',
'age': 16,
'grade': '10th'}
print(student_info.get('name'))
print(student_info.get('age'))
Output:
John
16
[ ] vs `.get()`
We can access dictionary elements by using square brackets with the key name, (e.g.student_info['name']
)
However, using .get()
is preferred because it doesn't cause an error if the key doesn't exist; it simply returns None
.
In contrast, using square brackets with an invalid key will raise a KeyError
and stop code execution
Updating a Dictionary
Update Method
We can update or add key-value pairs in a dictionary using the .update()
method.
The .update()
method takes in a dictionary as an argument where you can specify the key-value pair to be added or updated.
student_info = {'name': 'John',
'age': 16,
'grade': '10th'}
student_info.update({'age': 17})
print(student_info)
Output:
{'name': 'John', 'age': 17, 'grade': '10th'}
Adding a New Key-Value Pair
To add a new key-value pair, we simply assign a value to a new key in the dictionary.
student_info = {'name': 'John',
'age': 16,
'grade': '10th'}
student_info['school'] = 'High School'
print(student_info)
Output:
{'name': 'John', 'age': 16, 'grade': '10th', 'school': 'High School'}
Deleting from a Dictionary
There are two main ways to delete elements from a dictionary: using the .pop()
method or the del
keyword.
Pop Method
The .pop()
method removes the key-value pair associated with the specified key and returns the value.
student_info = {'name': 'John',
'age': 16,
'grade': '10th'}
student_info.pop('age')
print(student_info)
Output:
{'name': 'John', 'grade': '10th'}
Del Keyword
The del
keyword can be used to delete a key-value pair from a dictionary.
student_info = {'name': 'John',
'age': 16,
'grade': '10th'}
del student_info['grade']
print(student_info)
Output:
{'name': 'John', 'age': 16}
Del Trick
If you want to delete the entire dictionary, use del dictionary_name
.