Print a dictionary as a table

EasyDictionary Programs · 36 of 94

Write a Python program to print a dictionary of lists as a table.

Advertisement
Input
{"names": ["virat", "messi", "kobe"], "sport": ["cricket", "football", "basketball"]}
Output
   Names       Sport       
0  Virat       Cricket     
1  Messi       Football    
2  Kobe        Basketball  

Approach

  1. Print a header, then zip the columns into rows.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs