Python Iterate over a list
<p>trying to figure this one out,
i have 3 dictionaries and i am after adding them to a list, but how can i loop over list and print out that list.</p>

<pre><code>def_person = {'name' : 'TEST1','JobRole' : 'TESTJOB'}
def_person1 = {'name' : 'TEST2','JobRole' : 'TESTJOB1'}
def_person2 = {'name' : 'TEST3','JobRole' : 'TESTJOB2'}

person = list(def_person.keys())
person.append(def_person.values())
person.append(def_person1.values())
person.append(def_person2.values())

for persons in person:
    print()
</code></pre>

<p>so i the output would be like 
Name  jobrole with all the names under Name and job roles under jobrole.</p>

<p>Actually you cannot assume that all dictionaries having the same keys would display the keys in the same order - this is in no way guaranteed. Instead you should have a list of keys that you'd print in order, and then iterate over this key list for each dictionary, pulling values for each key.</p>

<p>I show how to make the two-dimensional list correctly first:</p>

<pre><code>person_keys = list(def_person.keys())

# add the heading row
result = [person_keys]

for person in [def_person, def_person1, def_person2]:
    # make a list of current person's values in the
    # order of keys in person_keys
    result.append([person[key] for key in person_keys])
</code></pre>

<p>Now, to print this list nicely, in Python 3 you can do:</p>

<pre><code>for row in result:
    for cell in row:
        # print each cell as at least 20 characters wide
        print('{:20}'.format(cell), end='')

    # empty line after each row
    print() 
</code></pre>

<p>Result:</p>

<pre><code>JobRole             name                
TESTJOB             TEST1               
TESTJOB1            TEST2               
TESTJOB2            TEST3               
</code></pre>

<hr>

<p>Above, the ordering of columns is arbitrary. Sometimes you will get <code>JobRole</code> first, sometimes <code>name</code> first. If you want to have a fixed order with <code>name</code> first, then just use <code>person_keys = ['name', 'JobRole']</code>,</p>

python python-3.x