Home > Software engineering >  Need assistance with Nested Loops and Dictionary in Python to display tabular data
Need assistance with Nested Loops and Dictionary in Python to display tabular data

Time:03-03

I have this sample data.

table_data = {
    "name": ['avery','john', 'jonas', 'jordan', 'terry', 'jared', 'evan'],
    "number": [0, 3, 8, 6, 12, 7, 11],
    "position": ['pg', 'sg', 'pf', 'pf', 'pg', 'c', 'sg'],
    "age": [25, 27, 29, 21, 22, 31, 27],
    "team": ['boston celtic',
             'boston celtic',
             'boston celtic',
             'boston celtic',
             'boston celtic',
             'boston celtic',
             'boston celtic', ],
            }

I want to display this data in tabular form with headings like in enter image description here

CodePudding user response:

So this is how I would go about doing this:

table_data = {
    "name": ['avery', 'john', 'jonas', 'jordan', 'terry', 'jared', 'evan'],
    "number": [0, 3, 8, 6, 12, 7, 11],
    "position": ['pg', 'sg', 'pf', 'pf', 'pg', 'c', 'sg'],
    "age": [25, 27, 29, 21, 22, 31, 27],
    "team": ['boston celtic',
             'boston celtic',
             'boston celtic',
             'boston celtic',
             'boston celtic',
             'boston celtic',
             'boston celtic', ],
}

for i in table_data["name"]:
    pos = table_data["name"].index(i)
    print(f"""{i}\t{table_data["age"][pos]}\t{table_data["position"][pos]}\t{table_data["team"][pos]}\t{table_data["number"][pos]}""")

Output:

avery   25  pg  boston celtic   0
john    27  sg  boston celtic   3
jonas   29  pf  boston celtic   8
jordan  21  pf  boston celtic   6
terry   22  pg  boston celtic   12
jared   31  c   boston celtic   7
evan    27  sg  boston celtic   11
  • Related