Dictionary Operations
Learn how to manage Python dictionaries by adding, updating, and removing entries, and checking key existence.
We'll cover the following...
We'll cover the following...
Adding and updating entries
We can add new entries in a dictionary by simply assigning a value to a key. Python automatically creates the entry. If a value already exists at this key, it will be updated:
Python 3.10.4
phone_book = {"Batman": 468426,"Cersei": 237734,"Ghostbusters": 44678}print(phone_book)phone_book["Godzilla"] = 46394print(phone_book)phone_book["Godzilla"] = 9000print(phone_book)
Removing entries
To delete an entry in a dictionary, we can use the del
keyword, which removes the key-value pair permanently. After using del
, the key will no longer exist in the dictionary, and trying to access it will result in a KeyError
. Here’s an example:
Python 3.10.4
phone_book = {"Batman": 468426,"Cersei": 237734,"Ghostbusters": 44678}print(phone_book)del phone_book["Batman"]print(phone_book)
If we want to use the deleted value, the ...