How to Replace Values in a Dictionary in Python (continued)

In a previous article, we have introduced replacing the values in the dictionary in Python, and this article will serve as a supplement to that article.

Article directory

    • Pass keyword arguments to the dict.update() method
    • Use dictionary unpacking to replace values in a dictionary
    • Use a for loop to replace values in a dictionary
    • Use the dictionary merge operator to replace values in a dictionary
    • Replace a value in a dictionary according to another dictionary
    • Using a dictionary comprehension to replace values in a dictionary

Use the dict.update() method to replace values in the dictionary, for example my_dict.update({'key': 'new value'}).

The dict.update() method updates the dictionary with the key-value pairs from the provided values.

my_dict = {<!-- -->
    'name': 'default',
    'site': 'default',
    'id': 1,
    'topic': 'Python'
}


my_dict.update(
    {<!-- -->'name': 'Ji Yi Ke',
     'site': 'jiyik.com'
    }
)

# ? {'name': 'Jiyik', 'site': 'jiyik.com', 'id': 1, 'topic': 'Python '}
print(my_dict)

We use the dict.update method to replace values in the dictionary.

The dict.update method updates the dictionary with the key-value pairs from the provided values.

This method overwrites the dictionary’s existing keys and returns None.

The dict.update() method can be called with another dictionary or an iterable of key-value pairs (e.g. a list with 2 elements per tuple).

Pass keyword arguments to the dict.update() method

We can also pass keyword arguments to the dict.update() method.

my_dict = {<!-- -->
    'name': 'default',
    'site': 'default',
    'id': 1,
    'topic': 'Python'
}


my_dict.update(
    [
        ('name', 'Ji Yi Ke'),
        ('site', 'jiyik.com')
    ]
)

# ? {'name': 'Jiyik', 'site': 'jiyik.com', 'id': 1, 'topic': 'Python '}
print(my_dict)

Alternatively, we can use the dictionary unpacking ** operator.

Using dictionary unpacking to replace values in the dictionary

To replace values in dictionary:

  1. Use the dictionary unpacking operator to unpack key-value pairs into a new dictionary.
  2. Specifies the key with the updated value.
  3. The new value will overwrite the existing key’s value.
my_dict = {<!-- -->
    'name': 'default',
    'site': 'default',
    'id': 1,
    'topic': 'Python'
}

my_dict = {<!-- -->
    **my_dict,
    'name': 'Ji Yi Ke',
    'site': 'jiyik.com'
}

# ? {'name': 'Jiyik', 'site': 'jiyik.com', 'id': 1, 'topic': 'Python '}
print(my_dict)

We use the dictionary unpacking ** operator to unpack the key-value pairs of a dictionary into a new dictionary.

The name and site keys override the values of existing keys with the same name.

Alternatively, we can use a for loop.

Use a for loop to replace values in the dictionary

To replace values in a dictionary:

  1. Use a for loop to iterate over the items of the dictionary.
  2. Check if each value should be updated.
  3. Replace matching values.
my_dict = {<!-- -->
    'name': 'default',
    'site': 'default',
    'id': 1,
    'topic': 'Python'
}

for key, value in my_dict.items():
    if value == 'default':
        if key == 'name':
            my_dict[key] = 'Ji Yi Ke'
        elif key == 'site':
            my_dict[key] = 'jiyik.com'


# ? {<!-- -->'name': 'Jiyik', 'site': 'jiyik.com', 'id': 1, ' topic': 'Python'}
print(my_dict)

The dict.items method returns a new view of the dictionary items ((key, value) pairs).

my_dict = {<!-- -->
    'name': 'default',
    'site': 'default',
    'id': 1,
    'topic': 'Python'
}

# ? dict_items([('name', 'default'), ('site', 'default'), ('id', 1), ('topic\ ', 'Python')])
print(my_dict. items())

In each iteration we check if the current value should be replaced and replace the matching value.

Using the dictionary merge operator to replace values in dictionaries

We can also use the dictionary merge operator to replace values in a dictionary.

my_dict = {<!-- -->
    'name': 'default',
    'site': 'default',
    'id': 1,
    'topic': 'Python'
}

my_dict = my_dict | {<!-- -->
    'name': 'Ji Yi Ke',
    'site': 'jiyik.com'
}

# {<!-- -->'name': 'Jiyik', 'site': 'jiyik.com',
# 'id': 1, 'topic': 'Python'}
print(my_dict)

The dictionary merge | operator is available since Python version 3.9.

We can check the Python version by running the following command.

$ python --version

The dictionary merge | operator creates a new dictionary.

This is also a dictionary update |= operator for assignment.

my_dict = {<!-- -->
    'name': 'default',
    'site': 'default',
    'id': 1,
    'topic': 'Python'
}

my_dict |= {<!-- -->
    'name': 'Ji Yi Ke',
    'site': 'jiyik.com'
}

# {'name': 'Jiyik', 'site': 'jiyik.com',
# 'id': 1, 'topic': 'Python'}
print(my_dict)

Make sure our Python version is 3.9 or higher to be able to run the code examples.

Replace a value in a dictionary according to another dictionary

We can also use a for loop to replace values in a dictionary based on another dictionary.

my_dict = {<!-- -->
    'name': 'default',
    'site': 'default',
    'id': 1,
    'topic': 'Python'
}

another_dict = {<!-- -->
    'name': 'Ji Yi Ke',
    'site': 'jiyik.com'
}

for key, value in another_dict.items():
    my_dict[key] = value

# ? {'name': 'Jiyik', 'site': 'jiyik.com',
# 'id': 1, 'topic': 'Python'}
print(my_dict)

We iterate over the items of the second dictionary using a for loop.

In each iteration, we replace the key-value pairs of the first dictionary.

We can also check if the key exists in the first dictionary.

my_dict = {<!-- -->
    'name': 'default',
    'site': 'default',
    'id': 1,
    'topic': 'Python'
}

another_dict = {<!-- -->
    'name': 'Ji Yi Ke',
    'site': 'jiyik.com',
    'abc': 'xyz',
    'one': 'two',
}

for key, value in another_dict.items():
    if key in my_dict:
        my_dict[key] = value

# ? {'name': 'Jiyik', 'site': 'jiyik.com',
# 'id': 1, 'topic': 'Python'}
print(my_dict)

In each iteration, we use the in operator to check if the current key is contained in the dictionary.

Keys are replaced only if they exist in the first dictionary.

Using a dictionary comprehension to replace values in a dictionary

We can also use a dictionary comprehension to replace values in a dictionary.

my_dict = {<!-- -->
    'name': 'default',
    'site': 'default',
    'id': 1,
    'topic': 'Python'
}

another_dict = {<!-- -->
    'name': 'Ji Yi Ke',
    'site': 'jiyik.com',
    'abc': 'xyz',
    'one': 'two',
}

my_dict = {<!-- -->
    key: another_dict. get(key, value)
    for key, value in my_dict.items()
}

# {'name': 'Jiyik', 'site': 'jiyik.com',
# 'id': 1, 'topic': 'Python'}
print(my_dict)

We use dictionary comprehensions to iterate over the items of the dictionary.

Dictionary comprehensions are very similar to list comprehensions.

They perform some operation on each key-value pair in the dictionary, or select a subset of key-value pairs that satisfy a condition.

In each iteration, we use the dict.get() method to get the value of the key in the second dictionary.

We specify the current value as a fallback in case the key doesn’t exist in the second dictionary.

The dict.get method returns the value for the given key if the key is in the dictionary, otherwise it returns the default value.

This method takes the following 2 parameters:

  • key The key to return a value for
  • default Returns the default value if the provided key does not exist in the dictionary (optional)
another_dict = {<!-- -->
    'name': 'Ji Yi Ke',
    'site': 'jiyik.com',
    'abc': 'xyz',
    'one': 'two',
}

print(another_dict.get('id')) # ? None
print(another_dict.get('topic')) # ? None

print(another_dict.get('name')) # ?

If no value is provided for the default parameter, it defaults to None, so the get() method never raises a KeyError.