Adding New Keys to a Dictionary
In Python, dictionaries are mutable and allow for the addition and deletion of key-value pairs. Unlike conventional data structures that offer an explicit .add() method, dictionaries handle key creation and assignment differently.
Solution
To add a new key to an existing dictionary, simply assign a value to the key:
d = {'key': 'value'} print(d) # {'key': 'value'} # Add a new key d['mynewkey'] = 'mynewvalue' print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
This operation has two outcomes:
Example
Consider the following code:
user_data = {'name': 'John Doe', 'age': 30} print(user_data) # {'name': 'John Doe', 'age': 30} # Add a new key to the dictionary user_data['email'] = 'john.doe@example.com' print(user_data) # {'name': 'John Doe', 'age': 30, 'email': 'john.doe@example.com'}
In this example, a new key 'email' is added to the 'user_data' dictionary, and it points to the value 'john.doe@example.com'.
The above is the detailed content of How Do I Add New Keys to a Python Dictionary?. For more information, please follow other related articles on the PHP Chinese website!