Open In App

Python | Updating value list in dictionary

Improve
Improve
Like Article
Like
Save
Share
Report

While working with dictionary with list as value is always vulnerable of getting it’s value updated. The ways or shorthands to perform this task can be handy in such situations. This can occur in web development domain. Let’s discuss certain ways in which this task can be performed.

 Method #1 : Using list comprehension 

The naive method to perform this particular task, in this, we just extract the key and then iterate over it’s value in list comprehensive format in packed list. This solved the problem. 

Python3




# Python3 code to demonstrate working of
# Updating value list in dictionary
# Using list comprehension
 
# Initialize dictionary
test_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Using list comprehension
# Updating value list in dictionary
test_dict['gfg'] = [x * 2 for x in test_dict['gfg']]
     
# printing result
print("Dictionary after updation is : " + str(test_dict))


Output

The original dictionary : {'gfg': [1, 5, 6], 'is': 2, 'best': 3}
Dictionary after updation is : {'gfg': [2, 10, 12], 'is': 2, 'best': 3}

Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

 Method #2 : Using map() + lambda 

This task can be performed using the combination of above two functions in which we use the map() to link the function of updation to each of element of value list and lambda is used to specify the updation. 

Python3




# Python3 code to demonstrate working of
# Updating value list in dictionary
# Using map() + lambda
 
# Initialize dictionary
test_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Using map() + lambda
# Updating value list in dictionary
test_dict['gfg'] = list(map(lambda x:x * 2, test_dict['gfg']))
     
# printing result
print("Dictionary after updation is : " + str(test_dict))


Output

The original dictionary : {'gfg': [1, 5, 6], 'is': 2, 'best': 3}
Dictionary after updation is : {'gfg': [2, 10, 12], 'is': 2, 'best': 3}

 Method #3 : Updating value list in dictionary Using update()

Python3




# Python3 code to demonstrate working of
# Updating value list in dictionary
# Using update()
   
# Initialize dictionary
test_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3}
   
# printing original dictionary
print("The original dictionary : " +  str(test_dict))
   
# Using update()
# Updating value list in dictionary
temp={'gfg':[x * 2 for x in test_dict['gfg']]}
test_dict.update(temp)
       
# printing result
print("Dictionary after updation is : " + str(test_dict))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original dictionary : {'gfg': [1, 5, 6], 'is': 2, 'best': 3}
Dictionary after updation is : {'gfg': [2, 10, 12], 'is': 2, 'best': 3}

Time complexity : O(n) 
Auxiliary Space : O(1)

Method #4: Using a for loop to update the value list in the dictionary

This method uses a for loop to iterate over the dictionary keys and check if the value is a list. If the value is a list, it updates the value list by multiplying each element by 2. This method is useful if you want to update the value list for multiple keys in the dictionary.

Python3




# Python3 code to demonstrate working of
# Updating value list in dictionary
# Using a for loop
 
# Initialize dictionary
test_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Using for loop
# Updating value list in dictionary
for key in test_dict:
    if isinstance(test_dict[key], list):
        test_dict[key] = [x * 2 for x in test_dict[key]]
     
# printing result
print("Dictionary after updation is : " + str(test_dict))


Output

The original dictionary : {'gfg': [1, 5, 6], 'is': 2, 'best': 3}
Dictionary after updation is : {'gfg': [2, 10, 12], 'is': 2, 'best': 3}

Time Complexity: O(NM) where N is the number of keys in the dictionary and M is the length of the value list. 
Auxiliary Space: O(1) because it updates the value list in place without creating a new list.

Method 5: Using the dict() constructor with a generator expression. 

Step-by-step approach:

  • Initialize the dictionary test_dict.
  • Use the dict() constructor with a generator expression to update the dictionary.
  • The generator expression iterates over key-value pairs in the original dictionary.
  • For each key-value pair, check if the value is a list using the isinstance() function.
  • If the value is a list, update the list by multiplying each element by 2 using a list comprehension.
  • If the value is not a list, leave it unchanged.
  • The updated dictionary is returned.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Updating value list in dictionary
# Using dict() constructor with generator expression
 
# Initialize dictionary
test_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3}
 
# Use dict() constructor with generator expression to update the dictionary
updated_dict = dict((k, [x * 2 for x in v]) if isinstance(v, list) else (k, v) for k, v in test_dict.items())
 
# Print the original and updated dictionaries
print("The original dictionary : " + str(test_dict))
print("Dictionary after updation is : " + str(updated_dict))


Output

The original dictionary : {'gfg': [1, 5, 6], 'is': 2, 'best': 3}
Dictionary after updation is : {'gfg': [2, 10, 12], 'is': 2, 'best': 3}

Time complexity: O(n) since we iterate over all key-value pairs in the dictionary once. 
Auxiliary space: O(n) as well, since we create a new dictionary object with updated values.

Method 6: Using a recursive function to update the value list in the dictionary

  1. The program initializes a dictionary called test_dict with three key-value pairs. The value for the gfg key is a list.
  2. The program defines a recursive function called update_dict that takes a dictionary as an argument.
  3. Inside the update_dict function, the program iterates through the items of the dictionary. If the value is a list, the program updates the list by multiplying each element in the list by 2 using a list comprehension. If the value is another dictionary, the program calls the update_dict function recursively on the nested dictionary. Otherwise, the program skips the iteration.
  4. The update_dict function returns the updated dictionary.
  5. The updated dictionary is stored in a new dictionary called updated_dict.
  6. Finally, the program prints the original and updated dictionaries.

Python3




# Python3 code to demonstrate working of
# Updating value list in dictionary
# Using a recursive function
 
# Initialize dictionary
test_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3}
 
# Define recursive function to update dictionary
def update_dict(d):
    for k, v in d.items():
        if isinstance(v, list):
            d[k] = [x * 2 for x in v]
        elif isinstance(v, dict):
            update_dict(v)
     
    return d
 
# Call update_dict function to update the dictionary
updated_dict = update_dict(test_dict)
 
# Print the original and updated dictionaries
print("The original dictionary : " + str(test_dict))
print("Dictionary after updation is : " + str(updated_dict))


Output

The original dictionary : {'gfg': [2, 10, 12], 'is': 2, 'best': 3}
Dictionary after updation is : {'gfg': [2, 10, 12], 'is': 2, 'best': 3}

Time complexity: O(n) where n is the number of key-value pairs in the dictionary.

Auxiliary space: O(n) for the recursive function call stack.



Last Updated : 27 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads