Search⌘ K
AI Features

Dictionary Operations

Explore Python dictionary operations to add, update, and delete entries, check key existence, copy contents between dictionaries, and create new dictionaries using comprehensions. Understand how to manage key-value pairs effectively and reinforce your skills with practical challenges.

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"] = 46394
print(phone_book)
phone_book["Godzilla"] = 9000
print(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 ...