python

Update dictionary values in python

To update or change the dictionary values, you need to assign the value to the relevant key.

my_car = {
  'modal': 'EV 34',
  'brand': 'TATA'
}

my_car['modal'] = 'RV 21'

print(my_car)
# -> {'modal': 'RV 21', 'brand': 'TATA'}

Update dictionary values in python. If you're working on a project that uses dictionaries, you'll almost certainly need to change the value of a particular key at some point or another. Knowing how to update dictionary values and when to use this technique can help make your code more efficient.

In the code snippet

We have defined a dictionary my_car that contains two keys - modal and brand

We are changing the value of the modal key using the below code

my_car['modal'] = 'RV 21'

Printing the dictionary with updated values.

Change dictionary values using update() function

You can also update or change dictionary values in python using the update() method. See below example

my_car = {
  'modal': 'EV 34',
  'brand': 'TATA'
}

my_car.update({'modal': 'RV 21'})

print(my_car)
# -> {'modal': 'RV 21', 'brand': 'TATA'}
Remember that all the methods described in this post will update the value to the relevant keys if they exist in the dictionary. If the key does not exist it will add a new key-value pair item in the python dictionary.
Was this helpful?