James Jameson
James Jameson

Reputation: 57

How do I turn a string into its value pairs from a dictionary?

I have a dictionary with 13 key value pairs as follows:

dict = {'a': 'd', 'b': 'e', 'c': 'f', 'g': 'j', 'h': 'k', 'i': 'l', 'm': 'p', 'n': 'q', 'o': 'r', 's': 'v', 't': 'w', 'u': 'x', 'y': 'z'}

I want to create a function that takes a string as an argument and returns a string containing the corresponding values.

I have tried this:

def encoding(x):
    for key in dict:
        print (dict[key])
print (encoding('abc'))

However I am getting the wrong output. Firstly its printing each key on a new line. Secondly it keeps printing the values, not just the ones corresponding with 'abc'. If the string passed to the function is 'abc' I want it to output 'def'.

Upvotes: 0

Views: 42

Answers (2)

Saurav Rai
Saurav Rai

Reputation: 2347

There are many ways to do that. Here I have given one solution as similar to what you have done. One problem with your solution was you were passing the keys of the dictionary and not the input characters of the string.

Also, remember a Dictionary has no guaranteed order, so you use it only to quickly lookup a key and find a corresponding value, or you enumerate through all the key-value pairs without caring what the order is.

dict = {'a': 'd', 'b': 'e', 'c': 'f'}
def encoding(x):
    for value in x:
        print (dict[value])
print (encoding('abc'))

Hope this helps you.

Upvotes: 1

GooT
GooT

Reputation: 70

Maybe this will help you

dict = {'a': 'd', 'b': 'e', 'c': 'f', 'g': 'j', 'h': 'k', 'i': 'l', 'm': 'p', 'n': 'q', 'o': 'r', 's': 'v', 't': 'w', 'u': 'x', 'y': 'z'}
def encoding(x):
    return ''.join(dict[ch] for ch in x)
print (encoding('abc'))

Upvotes: 1

Related Questions