Python Change Dictionary Item
A common task when working with dictionaries is updating or changing the values associated with specific keys. This article will explore various ways to change dictionary items in Python.
1. Changing a Dictionary Value Using Key
In Python, dictionaries allow us to modify the value of an existing key. This is done by directly assigning a new value to the key.
d = {1: 10, 2: 20, 3: 30}
d[2] = 25 # Change the value associated with key 2
print(d)
Output
{1: 10, 2: 25, 3: 30}
Here, the value for the key 2 is updated from 20 to 25.
Let's explore methods of changing dictionary items :
2. Using .update()
Method with a Dictionary
update() method allows us to update multiple key-value pairs at once. If a key already exists, it updates the value; if not it adds a new key-value pair.
d = {1: 10, 2: 20, 3: 30}
d.update({2: 22, 5: 50}) # Update key 2 and add key 5
print(d)
Output
{1: 10, 2: 22, 3: 30, 5: 50}
Here, the value of key 2 is updated to 22 and a new key 5 is added with the value 50.
3. Using .update()
Method with Keyword Arguments
# Define a dictionary
d = {'a': 10, 'b': 20, 'c': 30}
# Update the value of key 'b' using keyword arguments
d.update(b=25)
print(d)
Output
{'a': 10, 'b': 25, 'c': 30}
Table of Content
Adding New Key-Value Pairs
If the key does not already exist in the dictionary, simply assigning a value to a new key will add a new key-value pair to the dictionary.
d = {1: 10, 2: 20, 3: 30}
d[4] = 40 # Add a new key-value pair
print(d)
Output
{1: 10, 2: 20, 3: 30, 4: 40}
In this example, the key 4 is added with the value 40.
Changing Items Based on Conditions
We can modify dictionary values based on certain conditions making it more dynamic.
d = {1: 10, 2: 20, 3: 30}
if d[2] > 15:
d[4] = 40 # Add a new key if the value of key 2 is greater than 15
print(d)
Output
{1: 10, 2: 20, 3: 30, 4: 40}
In this example, the new key 4 is added if the value of key 2 is greater than 15.
Changing Multiple Items Using Dictionary Comprehension
If we need to change multiple items in a dictionary, we can use dictionary comprehension. This is helpful for transforming values based on conditions.
d1 = {1: 10, 2: 20, 3: 30}
# Double the values for keys greater than 1
d2 = {k: v * 2 if k > 1 else v for k, v in d1.items()}
print(d2)
Output
{1: 10, 2: 40, 3: 60}
In this case, the values for keys greater than 1 are doubled, while the value for key 1 remains unchanged.