Using numbers in a list to access items in a dictionary in python
<p>I have the items:</p>

<pre><code>my_list = [18, 15, 22, 22, 25, 10, 7, 25, 2, 22, 14, 10, 27]
</code></pre>

<p>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:</p>

<pre><code>my_dict = {1:"A", 2:"B", 3:"C" ... 26:"Z", 27:"_"}
</code></pre>

<p>How would I got about doing this? I have tried loops like this:</p>

<pre><code>for i in my_list:
    my_newlist = []
    letters = number_value[keys.index(i)]
    letters.append(my_newlist)
</code></pre>

<p>However I am getting errors in doing so. Cheers.</p>

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

<pre><code>for i in my_list:
    third_list = []
    num_val = keys[values.index(i)] + key_shift
    third_list.append(num_val)
    print(num_val)
</code></pre>

<p>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.</p>

<p>Encrypter is now working. You can find a version <a href="https://github.com/Bluestormy/Python/blob/master/Python%20Encrypter.py" rel="nofollow">here</a></p>

<p>You can simply use a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> where you implicitly loop through your list of numbers <code>my_list</code> and retrieve the value form your dict <code>my_dict</code> using the respective number as a key:</p>

<pre><code>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]
print(result)
</code></pre>

<p>yields</p>

<pre><code>['A', 'E', 'S']
</code></pre>

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

<pre><code>result = [my_dict[i] for i in my_list if i in my_dict.keys()]
print(result)
</code></pre>

python list dictionary