-1

I want to get keys name from values because I want to create a word encryptor decryptor program.

I want letter 'a' from value 1Q.

words = {
    'a' : '1Q',
    'b' : '2E',
    'c' : '3T',
    'd' : '4U',
    'e' : '5O',
    'f' : '6W',
    'g' : '7R',
    'h' : '8Y',
    'i' : '9I',
    'j' : '0P',
    'k' : 'A0',
    'l' : 'D1',
    'm' : 'G2',
    'n' : 'J3',
    'o' : 'L4',
    'p' : 'S5',
    'q' : 'F6',
    'r' : 'H7',
    's' : 'K8',
    't' : 'Z9',
    'u' : 'CC',
    'v' : 'BB',
    'w' : 'MM',
    'x' : 'XS',
    'y' : 'VZ',
    'z' : 'NS',
}

def Text_To_Hash(Text):
    val = ''
    Text_ = Text.lower()
    for i in Text_:
        if i == ' ':
            val += 'LK'
        else:
            val += str(words[i])
    return val

Input = input("Enter a value: ")

print(Text_To_Hash(Input))

There is no error. I want the key name from the value.

How do I solve the problem?

Emma
  • 27,428
  • 11
  • 44
  • 69
  • 1
    Possible duplicate of [this](https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary). Also, if you need to get more than one time the key from a value , I advice you to save the "inversed" dictionnary (keys come values and values come keys). Thus, you don't need to loop over the whole dict each time. – Alexandre B. Jul 13 '19 at 10:00
  • What did you try to decrypt the string? – Willem Van Onsem Jul 13 '19 at 10:00

2 Answers2

1

try for loop over the dictionary.

def Text_To_Hash(Text):
    val = ''
    Text_ = Text.lower()
    for i in Text_:
        for key in words:
            if words[key] == i:
                val += key
    return val
Shady Mohamed Sherif
  • 15,003
  • 4
  • 45
  • 54
hmn Falahi
  • 730
  • 5
  • 22
0

To do this efficiently (time, not space), I would suggest creating your own class, basically would be a wrapper around two different dictionaries. So, it might look something like this:

class TwoWayDict:
    def __init__(self):
        self.dict1 = {}
        self.dict2 = {}

    def insert(self, key, value):
        if key in self.dict1.keys() or key in self.dict2.keys():
            raise ....some exception about the key already existing....
        self.dict1[key] = value
        self.dict2[value] = key

    def getValueFromKey(self, key):
        return self.dict1[key]

    def getKeyFromValue(self, value):
        return self.dict2[value]

This obviously isn't fully fleshed out, but it shows the basic principle, I hope.

Axle12693
  • 46
  • 6