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
test_list = [ "Gfg" , "is" , "Best" ]
print ( "The original list : " + str (test_list))
subs_dict = {
"Gfg" : [ 5 , 6 , 7 ],
"is" : [ 7 , 4 , 2 ],
}
K = 2
res = [ele if ele not in subs_dict else subs_dict[ele][K]
for ele in test_list]
print ( "The list after substitution : " + str (res))
|
Output
The 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
test_list = [ "Gfg" , "is" , "Best" ]
print ( "The original list : " + str (test_list))
subs_dict = {
"Gfg" : [ 5 , 6 , 7 ],
"is" : [ 7 , 4 , 2 ],
}
K = 2
res = [subs_dict.get(ele, ele) for ele in test_list]
res = [ele[K] if isinstance (ele, list ) else ele for ele in res]
print ( "The list after substitution : " + str (res))
|
Output
The 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
test_list = [ "Gfg" , "is" , "Best" ]
print ( "The original list : " + str (test_list))
subs_dict = {
"Gfg" : [ 5 , 6 , 7 ],
"is" : [ 7 , 4 , 2 ],
}
K = 2
for i in range ( len (test_list)):
if test_list[i] in subs_dict:
test_list[i] = subs_dict[test_list[i]][K]
print ( "The list after substitution : " + str (test_list))
|
Output
The 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
test_list = [ "Gfg" , "is" , "Best" ]
print ( "The original list : " + str (test_list))
subs_dict = {
"Gfg" : [ 5 , 6 , 7 ],
"is" : [ 7 , 4 , 2 ],
}
K = 2
def replace_string(s):
return subs_dict[s][K] if s in subs_dict else s
res = list ( map (replace_string, test_list))
print ( "The list after substitution : " + str (res))
|
Output
The 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
test_list = [ "Gfg" , "is" , "Best" ]
print ( "The original list : " + str (test_list))
subs_dict = {
"Gfg" : [ 5 , 6 , 7 ],
"is" : [ 7 , 4 , 2 ],
}
K = 2
res = [subs_dict[x][K] if x in subs_dict else x for x in test_list]
print ( "The list after substitution : " + str (res))
|
Output
The 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
Python - Convert key-value String to dictionary
Sometimes, while working with Python strings, we can have problems in which we need to convert a string's key-value pairs to the dictionary. This can have applications in which we are working with string data that needs to be converted. Let's discuss certain ways in which this task can be performed.
4 min read
Python - Remove digits from Dictionary String Values List
We are given dictionary we need to remove digits from the dictionary string value list. For example, we are given a dictionary that contains strings values d = {'key1': ['abc1', 'def2', 'ghi3'], 'key2': ['xyz4', 'lmn5']} we need to remove digits from dictionary so that resultant output becomes {'key
3 min read
Python - Sort Dictionary by Values and Keys
Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically. Input : test_dict = {"gfg" : 1, "is" : 1, "best" : 1, "for" : 1, "geeks" : 1} Output : {"best" : 1, "is" : 1, "for" : 1, "geeks" : 1, "gfg" : 1} Explanation : All values are equal, hence lexico
3 min read
Python - Dictionary Tuple Values Update
The task of updating tuple values in a dictionary involves modifying each tuple in the dictionary by applying a specific operation to its elements. In this case, the goal is to update each element of the tuple based on a given condition, such as multiplying each element by a constant. For example, g
3 min read
Get Dictionary Value by Key - Python
We are given a dictionary and our task is to retrieve the value associated with a given key. However, if the key is not present in the dictionary we need to handle this gracefully to avoid errors. For example, consider the dictionary : d = {'name': 'Alice', 'age': 25, 'city': 'New York'} if we try t
3 min read