Kyle Kyle - 7 months ago 24
Python Question

Using numbers in a list to access items in a dictionary in python

I have the items:

my_list = [18, 15, 22, 22, 25, 10, 7, 25, 2, 22, 14, 10, 27]

in a list and I would like to use these to access items inside my dictionary by using a 'for loop', I will then append these items to a new list. My dictionary looks like this:

my_dict = {1:"A", 2:"B", 3:"C" ... 26:"Z", 27:"_"}

How would I got about doing this? I have tried loops like this:

for i in my_list:
my_newlist = []
letters = number_value[keys.index(i)]

However I am getting errors in doing so. Cheers.

In another area of my code I have the revers function, in which I get the key by searching for the item with:

for i in my_list:
third_list = []
num_val = keys[values.index(i)] + key_shift

It's being used in a substitution cypher code. The sample above works, it looks in the dictionary for the key which corresponds to "A" and stores the key in a list.

Encrypter is now working. You can find a version here


You can simply use a list comprehension where you implicitly loop through your list of numbers my_list and retrieve the value form your dict my_dict using the respective number as a key:

my_dict = {i: chr(i+64) for i in range(27)}
my_list = [1, 5, 19]

result = [my_dict[i] for i in my_list]


['A', 'E', 'S']

Make sure to check for KeyError, because your list my_list may contain numbers that are not present in your dict my_dict. If you want to avoid explicit exception handling (and silently omit missing keys), you can do something like this:

result = [my_dict[i] for i in my_list if i in my_dict.keys()]