Open In App

Python | Updating value list in dictionary

Last Updated : 27 Apr, 2023
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.



Similar Reads

Merging and Updating Dictionary Operators in Python 3.9
Python 3.9 is still in development and scheduled to be released in October this year. On Feb 26, alpha 4 versions have been released by the development team. One of the latest features in Python 3.9 is the merge and update operators. There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Pytho
3 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Python - Replace value by Kth index value in Dictionary List
Given a dictionary list, the task is to write a Python program to replace the value of a particular key with kth index of value if the value of the key is list. Examples: Input : test_list = [{'gfg' : [5, 7, 9, 1], 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : [7, 3, 9, 1]}], K = 2, key = "gfg" Output : [{'gfg':
7 min read
Python - Replace dictionary value from other dictionary
Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "Geeks" and "Best" values updated to 10 and 17. Inpu
6 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Retrieving And Updating Data Contained in Shelve in Python
In Python shelve you access the keys randomly. In order to access the keys randomly in python shelve we use open() function. This function works a lot like the file open() function in File handling. Syntax for open the file using Python shelve shelve.open(filename, flag='c' , writeback=True) In Order to access the keys randomly in shelve in Python,
3 min read
Updating dependencies in Python Poetry
Updating dependencies in Python Poetry is straightforward and efficient, thanks to its comprehensive command-line interface and powerful dependency resolution capabilities. Regularly updating your dependencies ensures that your project benefits from the latest features, bug fixes, and security improvements. Why Update Dependencies in Python Poetry?
3 min read
Python - Convert Key-Value list Dictionary to List of Lists
Sometimes, while working with a Python dictionary, we can have a problem in which we need to perform the flattening of a key-value pair of dictionaries to a list and convert it to a list of lists. This can have applications in domains in which we have data. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + item
8 min read
Practice Tags :