Change Dictionary Values in Python

Change Dictionary Values in Python

Muhammad Waiz Khan Feb-21, 2021 Jan-28, 2021 Python Python Dictionary
  1. Change Dictionary Values in Python Using the dict.update() Method
  2. Change Dictionary Values in Python Using the for Loop
  3. Change Dictionary Values in Python by Unpacking Dictionary Using the * Operator

This tutorial will look into multiple ways of changing the specific key’s value in the Python dictionary. We can do it by using the below methods,

  • the dict.update() method
  • the for loop,
  • dictionary unpacking method

Change Dictionary Values in Python Using the dict.update() Method

In this method, we pass the new key-value pairs to the update() method of the dictionary object. We can change one and more key-value pairs using the dict.update() method.

Example code:

my_dict = { 'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1}
print('Original:')
print(my_dict)

my_dict.update({'Khan': 6, 'Luna': 9})

print('\nAfter update:')
print(my_dict)

Output:

Original:
{'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1}

After update:
{'Khan': 6, 'Ali': 2, 'Luna': 9, 'Mark': 11, 'Pooja': 8, 'Sara': 1}

Change Dictionary Values in Python Using the for Loop

In this method, we keep iterating through the dictionary using the for loop until we find the key whose value needs to be modified. After getting the key, we can change the key’s value by assigning a new value to it.

Code example:

my_dict = { 'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1}

for key, value in my_dict.items():
    if key == 'Ali':
        my_dict[key] = 10

print(my_dict)

Output:

{'Khan': 4, 'Ali': 10, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1}

Change Dictionary Values in Python by Unpacking Dictionary Using the * Operator

In this method, we can change the dictionary values by unpacking the dictionary using the * operator and then adding the one or more key-value pairs we want to change the dictionary.

Note

the unpacking method actually creates a new dictionary, instead of updating the original one.

Example code:

my_dict = { 'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1}
my_dict = { **my_dict, 'Pooja': 12}
print(my_dict)

Output:

{'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 12, 'Sara': 1}

Related Article - Python Dictionary

  • Check if a Key Exists in a Dictionary in Python
  • Convert a Dictionary to a List in Python
  • Get All the Files of a Directory
  • Find Maximum Value in Python Dictionary
  • Delete a File and Directory in Python
  • Sort a Python Dictionary by Value