Reputation: 342
I have this following code:
d = {'one' : '11111111', 'two' : '01010101', 'three' : '10101010'}
string = '01010101 11111111 10101010'
text = ''
for key, value in d.items():
if value in string:
text += key
print(text)
output: onetwothree
however, my desired out put is the order of the string, so: twoonethree. Is this possible when using a dictionary in python? thanks!
Upvotes: 1
Views: 76
Reputation:
One solution is to split the string into a list and loop for every item in that list.
EDIT: The split() method returns a list of all words using a separator, in this case whitespace whitespace is used (You can call it as string.split() in case of whitespace by the way.)
dict = {'one' : '11111111', 'two' : '01010101', 'three' : '10101010'}
string = '01010101 11111111 10101010'
text = ''
for item in string.split(" "):
for key, value in dict.items():
if value == item:
text += key + " "
print(text)
output: two one three
Upvotes: 1
Reputation: 8066
Reversing your dict(d) will help:
val2key = {value: key for key, value in d.items()}
text = "".join(val2key[value] for value in string.split())
print(text)
twoonethree
Upvotes: 2