Adding results from a for loop to a dictionary , and then appending to a list
<p>I'm aware that this is really simply , but I'm struggling with this. Basically I want to add the results of a for loop inside a dicionary, so i can work the results on another function, which i can print the desired field based on the key value, </p>

<p>Example:</p>

<pre><code>    i = 0
    b = 0
    cc = []
    while True:
        i += 1
        b += 1
        abc = {b: i}
        cc.append(abc)
        if i == 3:
            break
</code></pre>

<p>Result : <code>[{1: 1}, {2: 2}, {3: 3}]</code></p>

<p>So, the expected result would be <code>[{"1": 1, "2": 2, "3": 3}]</code></p>

<p>This is for python 2.7</p>

<p>Based on your expected outcome, I would suggest this:</p>

<pre><code>cc = []
for i in range(0,3):
    cc.append({str(i): i})
</code></pre>

<p>But please note that you do <strong>NOT</strong> get a dictionary at the end of this loop... What you get is a list of dictionaries, each dictionary featuring only one key-value pair... <code>[{'1':1},{'2':2}]</code> is not the same as <code>{'1':1, '2':2}</code> and you will probably have problems using such a list of dictionaries.</p>

<p>So my guess is you want something more along the lines of this:</p>

<pre><code>cc = dict()
for i in range(0,3):
    cc[str(i)] = i
</code></pre>

<p>Please tell me if I misunderstood your problem or if you need more explanation for the solutions.</p>

python python-2.7