Home > Backend Development > Python Tutorial > How Do I Add New Keys to a Python Dictionary?

How Do I Add New Keys to a Python Dictionary?

Linda Hamilton
Release: 2024-12-10 06:36:18
Original
352 people have browsed it

How Do I Add New Keys to a Python Dictionary?

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'}
Copy after login

This operation has two outcomes:

  • If the key doesn't exist, it's created and assigned the provided value.
  • If the key already exists, its current value is overwritten with the new value.

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'}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template