Adding and Removing Items

tags: #python/documentation/dictionaries

Add and remove key-value pairs

Python dictionaries are dynamics. Therefore add new or remove old key:value pairs.

1. Adding new key-value pairs

To add a new key-value pair to a dictionary, you specify the name of the dictionary followed by the new key in square brackets along with the new value in an assignment statement:

dictionary[<new_key>] = <new_value>

2. Removing key-value pairs

To remove a key-value pair by a key, you use the del statement:

del dictionary[<key_to_remove>]

In this syntax, you specify the dictionary name and the key that you want to remove.

Modifying values in a key-value pair

To modify a value associated with a key, you specify the dictionary name with the existing key in square brackets and the new value associated with the key:

dictionary[<existing_key>] = <new_value>
Powered by Forestry.md