I have an arbitrary dictionary e.g.:
a_dict = {'A': 'a', 'B':b, 'C': 'h',...}
and an arbitrary list of strings e.g.:
a_list = ['Abgg', 'C><DDh', 'AdBs1A']
my aim now is to find some simple method or algorithm in python which substitutes the key elements from the dictionary with the corresponding values. Means 'A' is substituted by 'a' and so on. So the result would be the list:
a_result = ['abgg', 'h><DDh', 'adbs1a']
CodePudding user response:
use string.translate and str.maketrans
import string
translate_dict = {'A': 'a', 'B':'b', 'C': 'h'}
trans = str.maketrans(translate_dict)
list_before = ['Abgg', 'C><DDh', 'AdBs1A']
list_after = [s.translate(trans) for s in list_before]
CodePudding user response:
Maybe something like this?
lut = {'A': 'a', 'B':'b', 'C': 'h'}
words = ["abh", "aabbhh"]
result = ["".join(lut.get(l, "") for l in lut) for word in words]
as a side note, don't use variable names that are reserved keywords in python like list or dict.
