Using a dict to translate numbers to letters in python

Simply iterate through your alphabet string, and use a dictionary comprehension to create your dictionary

# Use a dictionary comprehension to create your dictionary
alpha_dict = {letter:idx for idx, letter in enumerate(alphabet)}

You can then retrieve the corresponding number to any letter using alpha_dict[letter], changing letter to be to whichever letter you want.

Then, if you want a list of letters corresponding to your num_list, you can do this:

[letter for letter, num in alpha_dict.items() if num in num_list]

which essentially says: for each key-value pair in my dictionary, put the key (i.e. the letter) in a list if the value (i.e. the number) is in num_list

This would return ['b', 'd', 'f'] for the num_list you provided

Leave a Comment