Home > Back-end >  Format dictionary as table
Format dictionary as table

Time:10-25

Straight to the point, I have a task in which I need to print dictionary data as table with spacing of "10" from each horizontal value. Printing out the first and last name is simple, but how to I separate each grade (Math, ProgVal, Sports)? So far my code only prints out all the grades vertically. Note that the grades are not int/float, but I cannot change that, because the task is to edit an existing code and that was already there as it is. Hope you can help. (I am new to python and of course I have google this, but the examples there are different from mine and I can't manage to reproduce the same results with my dictionary) EXPECTED RESULT: expected result

students = {('Ozols', 'Jānis'): {'Math': '10', 'ProgVal': '5', 'Sports': '5'},
        ('Krumiņa', 'Ilze'): {'Math': '7', 'ProgVal': '3', 'Sports': '6'},
        ('Liepa', 'Peteris'): {'Math': '3', 'ProgVal': '7', 'Sports': '7'},
        ('Lapsa', 'Maris'): {'Math': '10', 'ProgVal': '10', 'Sports': '3'}}

courses = ['Math', 'ProgVal', 'Sports']


def printGrades():
print("list of students:")
print("{:10} {:10} {:10} {:10} {:10}".format('first', 'last', 'Math', 'ProgVal', 'Sports'))
for lName, fName in students.keys():
    studentRecord = students[(lName, fName)]
    for course in studentRecord:
        print(studentRecord[course])


while True:
 print()
 command = input("command:> ")
 command = command.lower()

 if command == 'print':
    printGrades()
 elif command == 'done':
    break
print("DONE")

OUTPUT:

command:> print
list of students:
first      last       Math       ProgVal    Sports    
10
5
5
7
3
6
3
7
7
10
10
3

command:> 

CodePudding user response:

Your code formats the headings. But it doesn't format the data.

print("{:10} {:10} {Math:10} {ProgVal:10} {Sports:10}".format(lname, fname, **studentRecord))

You might want to right-align the numbers using :>10 instead of :10.

CodePudding user response:

Try this for your function:

def printGrades():
    print("list of students:")
    print(
        "{:10} {:10} {:10} {:10} {:10}".format(
            "first", "last", "Math", "ProgVal", "Sports"
        )
    )
    for key in students:
        values = students[key]
        print("{:10} {:10} {:10} {:10} {:10}".format(key[0], key[1], values["Math"], values["ProgVal"], values["Sports"]))

CodePudding user response:

You need to apply the format to every entry in the dictionary:

grid="{:10}"*(2 len(courses))
print(grid.format("First","Last",*courses))
for (lName,fName),scores in students.items():
    print(grid.format(fName,lName,*map(scores.get,courses)))

Output:

First     Last      Math      ProgVal   Sports    
Jānis     Ozols     10        5         5         
Ilze      Krumiņa   7         3         6         
Peteris   Liepa     3         7         7         
Maris     Lapsa     10        10        3 
  • Related