Using integers to access a key, value pairs in a dictionary?
<p>Question: how can i use integer to use as Keys for a dictionary?</p>

<p>Explanation:
I have a dictionary</p>

<pre><code>example = {}
</code></pre>

<p>I am populating it with key, value pairs of</p>

<pre><code>A: something
B: something
C: something
1: something
2: something
3: something
4: something
5: something
6: something
</code></pre>

<p>Now i need to iterate over the 1 - 6 entries of this dictionary</p>

<pre><code>for i in range(1,6):
        if self.compare(image1, example[i])&gt;0.8:
            return True
</code></pre>

<p>Now as the keys in original dictionary are strings, and here 'i' is in integer format, I am getting the error:</p>

<pre><code>if self.compare(image1, example[i])&gt;0.8:
    KeyError: 0
</code></pre>

<p>In the console window if I try to access the dictionary key with <code>example["1"]</code>, it shows me its content, but when I try to show it as <code>example[1]</code>, it shows me:</p>

<pre class="lang-none prettyprint-override"><code>print example[1]
Traceback (most recent call last):
  File "pydevd_comm.py", line 1080, in do_it
    result = pydevd_vars.evaluate_expression(self.thread_id, self.frame_id, self.expression, self.doExec)
  File "pydevd_vars.py", line 352, in evaluate_expression
    Exec(expression, updated_globals, frame.f_locals)
  File "pydevd_exec.py", line 3, in Exec
    exec exp in global_vars, local_vars
  File "&lt;string&gt;", line 1, in &lt;module&gt;
KeyError: 1
</code></pre>

<p>Convert the number to a string before trying to access the dictionary:</p>

<pre><code>for i in range(1,6):
    if self.compare(image1, example[str(i)]) &gt; 0.8:
        return True
</code></pre>

<p>Or create the dictionary using integer keys instead of strings for the keys that are numbers.</p>

python loops dictionary key key-value