-2

I have to create a dictionary, where the keys are letters of the alphabet, and the values are the indexed letters of a given string.

Example:

Given the string "BDFHJLCPRTXVZNYEIWGAKMUSQO" create the following dictionary:

translate: dict = { "A": "B", "B": "D", "C": "F", ... "Z": "O" } 
3
  • 3
    I refute that this would be a duplicate. The linked question which claims to be an answer is made from a list, not from a string. Commented 2 days ago
  • 2
    @Julien, how much more effort does the question I asked require? The answer is 0, but seems like this website ceased to be the place where programming noobs can ask questions freely, and became a place where elites like you who know everything is making a question into a forum itself. Commented 2 days ago
  • 1
    @Shadow0013 long-time python programmers may consider this a duplicate because both questions answers are not really about strings or lists, they are about iterables (lists and strings are both iterables, and iterable is what enables you to use zip). I don't really agree, the questions are different even when the answers are nearly the same, and this questions answer contains ascii_uppercase as a helpful bit which is not at all part of the other QA. Commented 2 days ago

1 Answer 1

5

The most straightforward way is probably to create a dict from zip()-ing the uppercase alphabet string (string.ascii_uppercase), and your target string:

import string translate = dict(zip(string.ascii_uppercase, "BDFHJLCPRTXVZNYEIWGAKMUSQO")) print(translate) 

Since your variable is named translate, you might be looking into creating a tr-like function. If so, you could also consider creating a translation table with str.make_trans() and then use that with str.translate() to encode your strings.

import string tr_table = str.maketrans(string.ascii_uppercase, "BDFHJLCPRTXVZNYEIWGAKMUSQO") print("HELLO WORLD".translate(tr_table)) # "PJVVY UYWVH" 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.