A Python dictionary (`dict`) is a collection of key-value pairs that allow fast data retrieval. For example:
infor = {"name": "tom", "age": 13, "sex": "male"}
Here, `”name”`, `”age”`, and `”sex”` are keys, and `”tom”`, `13`, and `”male”` are values.
1. Using `del` to Remove a Specific Key-Value Pair.
The most common way to delete a key-value pair is by using the `del` statement:
del infor["age"]
After execution, the dictionary becomes:
{"name": "tom", "sex": "male"}
This method removes only the specified key-value pair without affecting other data.
2. Understanding the Syntax Error in `del infor[“age”:13]`.
If you mistakenly write:
del infor["age":13]
Python will throw a `KeyError` because `“age”:13` is not a valid syntax for dictionary keys. Dictionary keys must be unique identifiers, such as strings or numbers.
3. `del infor` Deletes the Entire Dictionary.
If you execute:
del infor
The entire dictionary will be deleted, and any further access will result in:
NameError: name 'infor' is not defined
This means that `del` not only removes the dictionary’s contents but also deletes the variable itself.
4. Using `infor.clear()` to Empty the Dictionary.
Unlike `del`, the `clear()` method removes all key-value pairs while keeping the dictionary object intact:
infor.clear()
print(infor) # Output: {}
The dictionary still exists, but it is now empty.
5. Summary: Choosing the Right Method.
- ✅ Delete a specific key-value pair: `del infor[“age”]`.
- ❌ Incorrect syntax: `del infor[“age”:13]`.
- ❌ Delete the entire dictionary: `del infor`.
- ✅ Clear the dictionary but keep the variable: `infor.clear()`.
6. Demo Video.
You can watch the following demo video by select the subtitle to your preferred subtitle language.