-3

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.

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()

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

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
David
  • 239
  • 2
  • 3
  • 12

1 Answers1

2

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.

I show how to make the two-dimensional list correctly first:

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])

Now, to print this list nicely, in Python 3 you can do:

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() 

Result:

JobRole             name                
TESTJOB             TEST1               
TESTJOB1            TEST2               
TESTJOB2            TEST3               

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