Home>

I am writing a cryptographic program that changes a character string obtained from standard input according to certain rules.
Gets the dictionary key and displays the dictionary value if it does not match the standard input list character.

lis = list (input_lines)
dic = {"A": "4",
        "E": "3",
        "G": "6",
        "I": "1",
        "O": "0",
        "S": "5",
        "Z": "2"}
#print (lis)
#k = dic.keys ()
print (k)
for moji in lis:
    if dic! = moji:
        print (moji)
    else:
        print (dic [moji])


When executed with this code, even if the key is in the standard input, it is output as the standard input.
I don't know why.

  • Answer # 1

    The problem settings are a little unclear, but it seems possible to consider using str # translate.

    from string import ascii_uppercase
    table = str.maketrans (
        'AEGIOSZ', '4361052'
    )
    src = ascii_uppercase
    print (src)
    dst = src.translate (table)
    print (dst)

    ResultsWandbox

    ABCDEFGHIJKLMNOPQRSTUVWXYZ
    4BCD3F6H1JKLMN0PQR5TUVWXY2

  • Answer # 2

    Here is an example of using get () as a production piece.

    lis = list (input ())
    dic = {
        "A": "4",
        "E": "3",
        "G": "6",
        "I": "1",
        "O": "0",
        "S": "5",
        "Z": "2"
    }
    for moji in lis:
        tr = dic.get (moji)
        if tr is None:
            tr = moji
        print (moji, "->", tr)

    Addition:

    In response to comments,

    transed = [dic.get (moji, moji) for moji in lis]
    print (lis, "->", transed)

  • Answer # 3

    if dic! = mojiBecause it is a dictionary and letters, it will always be False.
    Since k is defined,if not moji in kshould be used.