Home  >  Article  >  Backend Development  >  How Can I Change a Key in a Python Dictionary?

How Can I Change a Key in a Python Dictionary?

DDD
DDDOriginal
2024-11-07 08:14:02990browse

How Can I Change a Key in a Python Dictionary?

Manipulating Dictionary Keys

In the realm of Python programming, dictionaries hold a prominent place as mutable data structures that map unique keys to their corresponding values. Occasionally, the need arises to alter the name of a key within a dictionary, a task that can be accomplished with remarkable ease.

Changing a Key in Two Steps

One approach involves a two-step process, where we first assign the value associated with the target key to a new key and then remove the original key:

dictionary = { "old_key": "value" }

# Step 1: Assign the value to a new key
dictionary["new_key"] = dictionary["old_key"]

# Step 2: Delete the old key
del dictionary["old_key"]

This method ensures that the value remains associated with the new key while discarding the old key.

Changing a Key in One Step

For those seeking a more concise solution, a one-step method is available:

dictionary["new_key"] = dictionary.pop("old_key")

This technique effortlessly updates the key, assigns the value to the new key, and removes the old key in a single operation. However, it is important to note that this method raises a KeyError if the specified old key does not exist in the dictionary. Additionally, this approach deletes the old key, making it unavailable for future use.

Example

To illustrate these methods, let us consider a sample dictionary:

dictionary = { 1: 'one', 2:'two', 3:'three' }

Using the one-step method, we can change the key from 1 to ONE:

dictionary['ONE'] = dictionary.pop(1)

The resulting dictionary will appear as follows:

{2: 'two', 3: 'three', 'ONE': 'one'}

Alternatively, if the old key no longer needs to be retained, we could use the two-step process:

dictionary['ONE'] = dictionary['1']
del dictionary['1']

This will yield the same result as the one-step method.

The above is the detailed content of How Can I Change a Key in a Python Dictionary?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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