Modifying Dictionary Values: Learn with Five Examples
You can change the value linked to a key in a dictionary by just assigning a new value to that key. Here are five examples showing how to do this:
- Modifying an existing value:
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict['b'] = 5
print(my_dict) # Output: {'a': 1, 'b': 5, 'c': 3}
- Modifying a value for a key that doesn't exist initially:
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict['d'] = 7
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 7}
- Modifying the value using a variable:
my_dict = {'a': 1, 'b': 2, 'c': 3}
new_value = my_dict['b'] + 5
my_dict['b'] = new_value
print(my_dict) # Output: {'a': 1, 'b': 7, 'c': 3}
- Modifying the value using a function:
def modify_value(value):
return value * 2
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict['c'] = modify_value(my_dict['c'])
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 6}
- Modifying the value for a nested dictionary:
my_dict = {'a': {'x': 1, 'y': 2}, 'b': {'x': 3, 'y': 4}}
my_dict['a']['y'] = 5
print(my_dict) # Output: {'a': {'x': 1, 'y': 5}, 'b': {'x': 3, 'y': 4}}
In each example, we change the value linked to a specific key in the dictionary as needed.