Python Practice › Dictionary Programs › Program 36
Print a dictionary as a table
Write a Python program to print a dictionary of lists as a table.
Input
{"names": ["virat", "messi", "kobe"], "sport": ["cricket", "football", "basketball"]}Output
Names Sport 0 Virat Cricket 1 Messi Football 2 Kobe Basketball
Approach
- Print a header, then zip the columns into rows.
Solution
d = {"names": ["virat", "messi", "kobe"], "sport": ["cricket", "football", "basketball"]}print(f"{'':3}" + "".join(f"{h.title():<12}" for h in d))for i, row in enumerate(zip(*d.values())): print(f"{i:<3}" + "".join(f"{cell.title():<12}" for cell in row))Output
Names Sport 0 Virat Cricket 1 Messi Football 2 Kobe Basketball
Line by line
Line 3
zip(*d.values()) turns the column lists into rows.
Learn the concept
New to this topic? Read the lesson, then come back.