'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:
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 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Raed Ali |
