Home > Back-end >  How to assign dictionary keys and values using a for loop?
How to assign dictionary keys and values using a for loop?

Time:09-23

A message is encoded by replacing each letter with its "mirror image": i.e. "A" becomes "Z", "B" becomes "Y", and so forth. Use a for loop to populate the dictionary so that it maps each letter to its mirror image. For example, <mapping["E"]> should return "V".

letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
mapping = {}

I've gotten this far but I don't know if the reverse portion of the code is supposed to be part of the for loop and the output gives me {0: 'Z', 1: 'Y', etc} rather than {A:Z, B:Y, etc}

reverse=letters[::-1]
for x in range (len(letters)):
    mapping[x]=reverse[x]
    print(mapping)

CodePudding user response:

If you're looking for a dictionary comprehension, i'd do this

cypher = { key:value for key,value in zip(letters, letters[::-1]) }

CodePudding user response:

letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

x = 0
list_letters = []
for i in letters:
    x = x   1
    n = letters.index(i)
    list_letters.append(n)
    y = letters[-x]
    list_letters.append(y)

print(list_letters)
  • Related