Open In App

Updating Value List in Dictionary - Python

Last Updated : 12 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

We are given a dictionary where the values are lists and our task is to update these lists, this can happen when adding new elements to the lists or modifying existing values in them. For example, if we have a dictionary with a list as a value like this: {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3} then the output will be {'gfg': [2, 10, 12], 'is': 2, 'best': 3}.

Using List Comprehension

In this method we extract the key and iterate over its value (which is a list) using a list comprehension and that allows us to modify each element in the list directly such as doubling the values.


Output
{'gfg': [2, 10, 12], 'is': 2, 'best': 3}

Explanation:

  • list comprehension [x * 2 for x in li['gfg']] iterates over each element in the list and multiplies it by 2.
  • dictionary value for the key 'gfg' is updated with the newly modified list.

Let's explore other methods to achieve the same:

Using map() + lambda

In this method, we combine map() with a lambda function to update the values in the dictionary where the values are lists. map() function applies the given function to each element in the list and modifying it as needed.


Output
{'gfg': [2, 10, 12], 'is': 2, 'best': 3}

Explanation: map(lambda x: x * 2, li['gfg']) applies the lambda function to each element in the list by multiplying each element by 2 then the list() function is used to convert the result of map() back into a list.

Using update()

In this method we are using the update() function to modify the values of a dictionary. We create a temporary dictionary with the updated list and then update the original dictionary with this new value using update().


Output
{'gfg': [2, 10, 12], 'is': 2, 'best': 3}

Using for loop

This method involves iterating through the dictionary using a for loop and for each key we check if the associated value is a list and if so, we update the list by multiplying each element by 2.


Output
{'gfg': [2, 10, 12], 'is': 2, 'best': 3}

Using the dict() constructor with a generator expression

In this method, we use the dict() constructor along with a generator expression. The generator iterates over each key-value pair in the original dictionary checking if the value is a list and if it is then it updates the list by multiplying each element by 2 otherwise the value remains unchanged.


Output
{'gfg': [2, 10, 12], 'is': 2, 'best': 3}



Practice Tags :

Similar Reads