Dictionary, Lists and Strings

A decoder based on a Dictionary, it gets input as a List and splits it into single Strings so the Dictionary can be called to translate.

I know there’s a way to simplify the code and make it drastically smaller but I don’t know how.

Probably I should use the index in variable along with len() to make it smaller but couldn’t find a way around it.

Yes I’am new to programming.

Thanks in advance!

decoder = {
"96": "0",
"97": "1",
"98": "2",
"99": "3",
"100": "4",
"101": "5",
"102": "6",
"103": "7",
"104": "8",
"105": "9",
}
test = list(str(num) for num in 
input("Enter the list items 
separated by space: 
").strip().split()).
length = len(test)
if length == 1:
    a, = test
    print(decoder[a])
elif length == 2:
    a, b = test
    print(decoder[a])
    print(decoder[b])
elif length == 3:
    a, b, c = test
    print(decoder[a])
    print(decoder[b])
    print(decoder[c])
elif length == 4:
    a, b, c, d = test
    print(decoder[a])
    print(decoder[b])
    print(decoder[c])
    print(decoder[d])
elif length == 5:
    a, b, c, d, e = test
    print(decoder[a])
    print(decoder[b])
    print(decoder[c])
    print(decoder[d])
    print(decoder[e])
elif length == 6:
    a, b, c, d, e, f = test
    print(decoder[a])
    print(decoder[b])
    print(decoder[c])
    print(decoder[d])
    print(decoder[e])
    print(decoder[f])
elif length == 7:
    a, b, c, d, e, f, g = test
    print(decoder[a])
    print(decoder[b])
    print(decoder[c])
    print(decoder[d])
    print(decoder[e])
    print(decoder[f])
    print(decoder[g])
elif length == 8:
    a, b, c, d, e, f, g, h = test
    print(decoder[a])
    print(decoder[b])
    print(decoder[c])
    print(decoder[d])
    print(decoder[e])
    print(decoder[f])
    print(decoder[g])
    print(decoder[h])
elif length == 9:
    a, b, c, d, e, f, g, h, i = 
    test
    print(decoder[a])
    print(decoder[b])
    print(decoder[c])
    print(decoder[d])
    print(decoder[e])
    print(decoder[f])
    print(decoder[g])
    print(decoder[h])
    print(decoder[i])
elif length == 10:
    a, b, c, d, e, f, g, h, i, j = 
    test
    print(decoder[a])
    print(decoder[b])
    print(decoder[c])
    print(decoder[d])
    print(decoder[e])
    print(decoder[f])
    print(decoder[g])
    print(decoder[h])
    print(decoder[i])
    print(decoder[j])

>Solution :

You can use in , the same you did to create the list out of the inputted items, and use a for loop to iterate through those items:

decoder = {
"96": "0",
"97": "1",
"98": "2",
"99": "3",
"100": "4",
"101": "5",
"102": "6",
"103": "7",
"104": "8",
"105": "9",
}

test = [str(num) for num in input("Enter the list items separated by space: ").strip().split()]

for item in test:
    print(decoder[item])

Also, note how I defined test using list comprehension 🙂

Leave a Reply