Python - Replace String by Kth Dictionary value
Last Updated :
05 Apr, 2023
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.
Input : test_list = ["Gfg", "is", "Best"], subs_dict = {"Gfg" : [5, 6, 7], "Best" : [7, 4, 2]}, K = 0
Output : [5, "is", 7]
Explanation : "Gfg" and "Best" is replaced by 5, 7 as 0th index in dictionary value list.
Method #1: Using list comprehension
This is one of the ways in which this task can be performed. In this, we perform the task iteration and conditional replacement inside a one-liner in list comprehension.
Python3
# Python3 code to demonstrate working of
# Replace String by Kth Dictionary value
# Using list comprehension
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {
"Gfg" : [5, 6, 7],
"is" : [7, 4, 2],
}
# initializing K
K = 2
# using list comprehension to solve
# problem using one liner
res = [ele if ele not in subs_dict else subs_dict[ele][K]
for ele in test_list]
# printing result
print("The list after substitution : " + str(res))
OutputThe original list : ['Gfg', 'is', 'Best']
The list after substitution : [7, 2, 'Best']
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using get() + list comprehension
The combination of above functions can be used to solve this problem. In this, we iterate using list comprehension and check for key existence and substitution using get().
Python3
# Python3 code to demonstrate working of
# Replace String by Kth Dictionary value
# Using get() + list comprehension
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {
"Gfg" : [5, 6, 7],
"is" : [7, 4, 2],
}
# initializing K
K = 2
# using list comprehension to solve problem using one liner
# get() to perform presence checks and assign default value
res = [subs_dict.get(ele, ele) for ele in test_list]
res = [ele[K] if isinstance(ele, list) else ele for ele in res]
# printing result
print("The list after substitution : " + str(res))
OutputThe original list : ['Gfg', 'is', 'Best']
The list after substitution : [7, 2, 'Best']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using a loop
Use a for loop to iterate through the list and check if the current element is present in the subs_dict. If it is, then replace the current element with the Kth value from the dictionary.
Python3
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {
"Gfg" : [5, 6, 7],
"is" : [7, 4, 2],
}
# initializing K
K = 2
# using for loop to solve problem
for i in range(len(test_list)):
if test_list[i] in subs_dict:
test_list[i] = subs_dict[test_list[i]][K]
# printing result
print("The list after substitution : " + str(test_list))
OutputThe original list : ['Gfg', 'is', 'Best']
The list after substitution : [7, 2, 'Best']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using map() function
Another way to replace the strings in a list with the k-th value from the dictionary is to use the map() function, which takes a function and an iterable as arguments and applies the function to each element of the iterable.
Here's how you can use map() to solve this problem:
- Define a function replace_string that takes a string s as input and returns either the value at the k-th index of the dictionary if the string is a key in the dictionary, or the original string if it is not.
- Use the map() function to apply replace_string to each element of the list test_list.
- Convert the result of the map() function back to a list using the list() function.
- Print the resulting list.
Python3
# Python3 code to demonstrate working of
# Replace String by Kth Dictionary value
# Using map() function
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {
"Gfg" : [5, 6, 7],
"is" : [7, 4, 2],
}
# initializing K
K = 2
# define function to replace string
def replace_string(s):
return subs_dict[s][K] if s in subs_dict else s
# using map() function to solve problem
res = list(map(replace_string, test_list))
# printing result
print("The list after substitution : " + str(res))
OutputThe original list : ['Gfg', 'is', 'Best']
The list after substitution : [7, 2, 'Best']
Time complexity: O(n), where n is the length of the input list test_list since we need to apply the replace_string function to each element of the list.
Auxiliary space: O(n), since we create a new list res with the same length as test_list to store the result.
Method #7: Using a dictionary comprehension
Step-by-step approach:
- Use a dictionary comprehension to replace each string in test_list with its Kth element in subs_dict, if the string is present as a key in the dictionary, otherwise, leave the string unchanged.
- Store the resulting list in the variable res.
- Print the updated list res.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Replace String by Kth Dictionary value
# Using dictionary comprehension
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {
"Gfg" : [5, 6, 7],
"is" : [7, 4, 2],
}
# initializing K
K = 2
# using dictionary comprehension to solve problem
res = [subs_dict[x][K] if x in subs_dict else x for x in test_list]
# printing result
print("The list after substitution : " + str(res))
# Time complexity: O(n), where n is the length of the input list
# Auxiliary space: O(n), since we are creating a new list of the same length as the input list.
OutputThe original list : ['Gfg', 'is', 'Best']
The list after substitution : [7, 2, 'Best']
Time complexity: O(n), where n is the length of the input list
Auxiliary space: O(n), since we are creating a new list of the same length as the input list.
Similar Reads
Python Update Dictionary Value by Key A Dictionary in Python is an unordered collection of key-value pairs. Each key must be unique, and you can use various data types for both keys and values. Dictionaries are enclosed in curly braces {}, and the key-value pairs are separated by colons. Python dictionaries are mutable, meaning you can
3 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
7 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 - 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 : "G
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