Open In App

Python – Replace String by Kth Dictionary value

Last Updated : 05 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


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




# 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))


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




# 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))


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:

  1. 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.
  2. Use the map() function to apply replace_string to each element of the list test_list.
  3. Convert the result of the map() function back to a list using the list() function.
  4. 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))


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




# 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.


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.



Next Article

Similar Reads

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 Program to Remove Nth element from Kth key's value from the dictionary
Given a dictionary with value lists, our task is to write a Python program to remove N element from Kth key's values. Examples: Input : test_dict = {"gfg" : [9, 4, 5, 2, 3, 2], "is" : [1, 2, 3, 4, 3, 2], "best" : [2, 2, 2, 3, 4]}, K, N = "gfg", 2Output : {'gfg': [9, 4, 5, 3], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}Explanation : 2 removed
9 min read
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 can be solved. Input : test_dict = {'Gfg' : [10,
9 min read
Python - How to Sort a Dictionary by Kth Index Value
While working with Python, one might come to a problem in which one needs to perform a sort on a dictionary based on Kth index of value list. This can be typically in the case of scoring or web development. Let’s discuss a method by which this task can be performed. Input : test_dict = {'gfg' : [5, 6, 7], 'is' : [1, 4, 7], 'best' : [8, 3, 1]}, K =
6 min read
Python - Extract Kth index elements from Dictionary Value list
Given a dictionary with list as values, extract all the Kth index elements. Input : {"Gfg" : [4, 7, 5], "Best" : [8, 6, 7], "is" : [9, 3, 8]}, K = 2 Output : [5, 7, 8] Explanation : The 2nd index elements are 5, 7 and 8 respectively in different keys. Input : {"Gfg" : [4, 7, 5], "Best" : [8, 6, 7], "is" : [9, 3, 8]}, K = 0 Output : [4, 8, 9] Explan
7 min read
Python - Key with Maximum element at Kth index in Dictionary Value List
Given a dictionary with values as lists, the task is to write a Python program to get the key with the maximum element at the Kth index by comparing the elements of each list. Input : test_dict = {'Gfg' : [4, 6, 8, 2], 'is' : [1, 4, 5, 9], 'best' :[2, 3, 4, 10], 'for' :[4, 5, 2, 1], 'geeks' :[2, 10, 1, 8]}, K = 3 Output : best Explanation : 2, 9, 1
8 min read
Python - Kth word replace in String
Sometimes, while working with String list, we can have a problem in which we need to replace the most Kth word of string. This problem has many applications in the web development domain. Let’s discuss a way in which this problem can be solved. Method 1: Using split() + join() This is way in which we can perform this task. In this, we break element
6 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
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
three90RightbarBannerImg