Python - Replace value by Kth index value in Dictionary List
Last Updated :
05 Apr, 2023
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': 9, 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': 9}]
Explanation : gfg is assigned with 9 which is 2nd index in list.
Input : test_list = [{'gfg' : [5, 7, 9, 1], 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}], K = 2, key = "gfg"
Output : [{'gfg': 9, 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}]
Explanation : gfg is assigned with 9 which is 2nd index in list.
Method #1 : Using loop + isinstance()
Use isinstance() to check for list type of values and loop is used to iterate through dictionaries.
Step-by-step approach :
- Loop over each dictionary sub in the list test_list.
- Use the isinstance() function to check if the value corresponding to the key key is a list in the current dictionary sub.
- If the value is a list, update the value corresponding to the key key with the Kth element of the list.
- Print the modified list of dictionaries test_list.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Replace value by Kth index value in Dictionary List
# Using loop + isinstance()
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': [7, 3, 9, 1]}]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# initializing Key
key = "gfg"
for sub in test_list:
# using isinstance() to check for list
if isinstance(sub[key], list):
sub[key] = sub[key][K]
# printing result
print("The Modified Dictionaries : " + str(test_list))
OutputThe original list is : [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': [7, 3, 9, 1]}]
The Modified Dictionaries : [{'gfg': 9, 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': 9}]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using dictionary comprehension + isinstance()
In this, we reconstruct dictionaries with modified dictionary values using isinstance() and dictionary comprehension is used to form intermediate dictionaries.
Python3
# Python3 code to demonstrate working of
# Replace value by Kth index value in Dictionary List
# Using dictionary comprehension + isinstance()
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': [7, 3, 9, 1]}]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# initializing Key
key = "gfg"
# intermediate Dictionaries constructed using dictionary comprehension
res = [{newkey: (val[K] if isinstance(val, list) and newkey == key else val)
for newkey, val in sub.items()} for sub in test_list]
# printing result
print("The Modified Dictionaries : " + str(res))
OutputThe original list is : [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': [7, 3, 9, 1]}]
The Modified Dictionaries : [{'gfg': 9, 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': 9}]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 3: Modifying the original list in-place using a list comprehension:
This approach uses a list comprehension to create a new list of dictionaries with the specified key updated at index K, and then assigns the new list back to the original variable to modify it in-place. The output of this code should match exactly with the original program.
Python3
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': [7, 3, 9, 1]}]
# printing original list
print("The original list is : " + str(test_list))
# initializing K and key
K = 2
key = "gfg"
# modifying the original list in-place using a list comprehension
test_list = [{k: (v[K] if k == key and isinstance(v, list) else v) for k, v in d.items()} for d in test_list]
# printing result
print("The Modified Dictionaries : " + str(test_list))
OutputThe original list is : [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': [7, 3, 9, 1]}]
The Modified Dictionaries : [{'gfg': 9, 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': 9}]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using for loop and try-except block
we can use a for loop to iterate over the dictionaries in the list, and a try-except block to check if the key is present and if the value is a list. If the conditions are satisfied, we can replace the value with the K-th element of the list.
Python3
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': [7, 3, 9, 1]}]
# printing original list
print("The original list is : " + str(test_list))
# initializing K and key
K = 2
key = "gfg"
# using for loop and try-except block
for d in test_list:
try:
if isinstance(d[key], list):
d[key] = d[key][K]
except KeyError:
pass
# printing result
print("The Modified Dictionaries : " + str(test_list))
OutputThe original list is : [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': [7, 3, 9, 1]}]
The Modified Dictionaries : [{'gfg': 9, 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': 9}]
Time complexity: O(nm)
Where n is the number of dictionaries in the list and m is the maximum number of keys in any dictionary. This is because we need to iterate over each dictionary in the list and check each key to see if it matches the given key and whether the value is a list.
Auxiliary space: O(1)
Because we are not creating any additional data structures. We are only modifying the existing list in place.
Method #5: Using map() function and lambda expression
- Initialize the original list test_list with the given dictionaries.
- Print the original list.
- Initialize the index K with the given value. Initialize the key with the given value.
- Use the map() function to modify the original list in place.
- The map() function takes two arguments: a function and an iterable. In this case, the function is a lambda expression that modifies each sub-dictionary in the list. The iterable is the original list itself.
- The lambda expression checks if the value of the key is a list. If it is, then it updates the value of the key to be the Kth index value of the list. Otherwise, it does nothing.
- The map() function returns an iterator that applies the lambda function to each element of the list. However, since we don't need the iterator, we discard it using the list() function.
- Print the modified list.
Python3
# Python3 code to demonstrate working of
# Replace value by Kth index value in Dictionary List
# Using map() + lambda
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': [7, 3, 9, 1]}]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# initializing Key
key = "gfg"
# using map() function to modify the original list in-place
list(map(lambda sub: sub.update({key: sub[key][K]}) if isinstance(
sub[key], list) else None, test_list))
# printing result
print("The Modified Dictionaries : " + str(test_list))
OutputThe original list is : [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': [7, 3, 9, 1]}]
The Modified Dictionaries : [{'gfg': 9, 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': 9}]
Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(1), as the modification is done in-place without any additional data structure.
Similar Reads
Python - Test Kth index in Dictionary value list
Sometimes, while working with Python dictionaries, we can have a problem in which we need to test if, throughout the dictionary, the kth index of all values in the dictionary is equal to N. This kind of problem can occur in the web development domain. Let's discuss certain ways in which this problem
9 min read
Python - Replace String by Kth Dictionary value
Given a list of Strings, replace the value mapped with the Kth value of mapped list. Input : test_list = ["Gfg", "is", "Best"], subs_dict = {"Gfg" : [5, 6, 7], "is" : [7, 4, 2]}, K = 0 Output : [5, 7, "Best"] Explanation : "Gfg" and "is" is replaced by 5, 7 as 0th index in dictionary value list. Inp
6 min read
Python - Sort Dictionary List by Key's ith Index value
Given List of dictionaries, sort dictionaries on basis of Key's ith index value Input : [{"Gfg" : "Best", "for" : "Geeks"}, {"Gfg" : "Good", "for" : "Me"}, {"Gfg" : "Better", "for" : "All"}], K = "Gfg", i = 1 Output : [{'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Better', 'for': 'All'}, {'Gfg': 'Good',
7 min read
Python - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [
14 min read
Python - Filter dictionaries by values in Kth Key in list
Given a list of dictionaries, the task is to write a Python program to filter dictionaries on basis of elements of Kth key in the list. Examples: Input : test_list = [{"Gfg" : 3, "is" : 5, "best" : 10}, {"Gfg" : 5, "is" : 1, "best" : 1}, {"Gfg" : 8, "is" : 3, "best" : 9}, {"Gfg" : 9, "is" : 9, "best
9 min read
Dictionary items in value range in Python
In this article, we will explore different methods to extract dictionary items within a specific value range. The simplest approach involves using a loop.Using LoopThe idea is to iterate through dictionary using loop (for loop) and check each value against the given range and storing matching items
2 min read
Slice till K Dictionary Value Lists - Python
The task of slicing the values in a dictionary involves extracting a portion of the list associated with each key, up to a specified index k. This can be achieved by iterating over the dictionary, slicing each list up to the k-th index and storing the result in a new dictionary. For example, given a
4 min read
Python - Reinitialize Value lists to K in Dictionary
Sometimes, while working with Python dictionary values, we can have a problem in which we need to reinitialize all the values lists of all keys in dictionary to a constant K. This kind of problem can have application in domains which use data, like Machine Learning and Data Science. Let's discuss ce
6 min read
Python Remove Item from Dictionary by Value
We are given a dictionary and our task is to remove key-value pairs where the value matches a specified target. This can be done using various approaches, such as dictionary comprehension or iterating through the dictionary. For example: d = {"a": 10, "b": 20, "c": 10, "d": 30} and we have to remove
3 min read
Updating Value List in Dictionary - Python
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} the
3 min read