Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need assistance with Nested Loops and Dictionary in Python to display tabular data

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 this picture, of course without table borders.

In order to do that I used this code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for items in table_data:
    i = 0
    while i <= len(table_data['name']):
        print(table_data['name'][i],
              table_data['age'][i],
              table_data['position'][i],
              table_data['team'][i],
              table_data['number'][i],)
        i += 1
    print()

it gave me this output:

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

Before I end, I would like you to know I am not really good with both dictionary and nested loops and I avoid both as much as possible.
PS – It’s for learning purposes.

Thanks in advance.

>Solution :

Your code gave me some errors, fixed those.

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 = 0
while i < len(table_data):
    print(f"{table_data['name'][i]}\t {table_data['age'][i]}\t {table_data['position'][i]}\t {table_data['team'][i]}\t {table_data['number'][i]}")
    i += 1
print()

I guess this is what you were looking for.

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading