-2

quick explanation of what im trying to do. I've been wondering how to inverse a dictionary as im trying to make a Monoalphabetic cipher which will help me for a challenge soon. My aim after learning how to inverse a dictionary is to be able to use that to swap letters in a string.

This is what i have right now not much at all but it would be awesome if someone could help me out as i've been trying for a long time but i have no idea how to.

dicta = {
    'a': 'M',
    'b': 'N',
    'c': 'B',
    'd': 'V',
    'e': 'C',
    'f': 'X',
    'g': 'Z',
    'h': 'A',
    'i': 'S',
    'j': 'D',
    'k': 'F',
    'l': 'G',
    'm': 'H',
    'n': 'J',
    'o': 'K',
    'p': 'L',
    'q': 'P',
    'r': 'O',
    's': 'I',
    't': 'U',
    'u': 'Y',
    'v': 'T',
    'w': 'R',
    'x': 'E',
    'y': 'W',
    'z': 'Q',
    ' ': ' ',
}
print(dicta)
Ivan
  • 117
  • 1
  • 1
  • 9

1 Answers1

0

The others gave you the inversion. Replacement is easy with a list comprehension:

dicta = { # as above }
dictb = {v: k for k, v in dicta.items()}
orig_str = # your original text
# Make a list of translated characters: 
#   if the char is in the dictionary, use the translation;
#   otherwise, use the original.
new_char_list = [dicta[char] if char in dicta else char \
                 for char in orig_str]
# Join the translated list into a string.
new_str = ''.join(new_char_list)

You can combine the last two assignments if you like, but I thought it would be easier to understand as separate statements.

EDIT PER OP's COMMENT

No problem; this is how we learn. Unraveling the list comprehension from the inside out, the code would look something like this:

new_char_list = []
for char in old_string:
    if char in dicta:      # is this character in the dictionary?
        new_char = dicta[char]
    else:
        new_char = char

    new_char_list += [char]

The **if** statement lets you handle characters that you didn't put into the dictionary: punctuation, for example.

Does that clear up the confusion for you?

Prune
  • 76,765
  • 14
  • 60
  • 81
  • Although i kinda get this im not very familiar with dictionarys as im new to python. what do you mean by make a list as in lista = (a,b,c,d) and what do you mean by :if the char is in the dictionary, use the translation; # otherwise, use the original. Im sorry that i might be a pain but with out asking i wont learn and im not an expert in python and i dont have anyone else to ask – Ivan Jan 19 '17 at 23:33