pythonstringdictionary

How to create a dictionary where the keys are the alphabet (A-Z), and values are a letter from a string in Python?


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"
}

Solution

  • 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"