Python program to print the dictionary in table format
Last Updated :
01 Aug, 2022
Given a Dictionary. The task is to print the dictionary in table format.
Examples:
Input:
{1: ["Samuel", 21, 'Data Structures'],
2: ["Richie", 20, 'Machine Learning'],
3: ["Lauren", 21, 'OOPS with java'],
}
Output:
NAME AGE COURSE
Samuel 21 Data Structures
Richie 20 Machine Learning
Lauren 21 OOPS with java
Method 1: Displaying results by iterating through values.
Python3
dict1 = {}
dict1 = { 1 : [ "Samuel" , 21 , 'Data Structures' ],
2 : [ "Richie" , 20 , 'Machine Learning' ],
3 : [ "Lauren" , 21 , 'OOPS with java' ],
}
print ( "{:<10} {:<10} {:<10}" . format ( 'NAME' , 'AGE' , 'COURSE' ))
for key, value in dict1.items():
name, age, course = value
print ( "{:<10} {:<10} {:<10}" . format (name, age, course))
|
Output
NAME AGE COURSE
Samuel 21 Data Structures
Richie 20 Machine Learning
Lauren 21 OOPS with java
Method 2: Displaying by using a matrix format
Python3
dict1 = {}
dict1 = {( 0 , 0 ): 'Samuel' , ( 0 , 1 ): 21 , ( 0 , 2 ): 'Data structures' ,
( 1 , 0 ): 'Richie' , ( 1 , 1 ): 20 , ( 1 , 2 ): 'Machine Learning' ,
( 2 , 0 ): 'Lauren' , ( 2 , 1 ): 21 , ( 2 , 2 ): 'OOPS with Java'
}
print ( " NAME " , " AGE " , " COURSE " )
for i in range ( 3 ):
for j in range ( 3 ):
print (dict1[(i, j)], end = ' ' )
print ()
|
Output
NAME AGE COURSE
Samuel 21 Data structures
Richie 20 Machine Learning
Lauren 21 OOPS with Java
Method 3: Displaying by using zip format
Python3
dict1 = {}
dict1 = { 'NAME' : [ 'Samuel' , 'Richie' , 'Lauren' ],
'AGE' : [ 21 , 20 , 21 ],
'COURSE' : [ 'Data Structures' , 'Machine Learning' , 'OOPS with Java' ]}
for each_row in zip ( * ([i] + (j)
for i, j in dict1.items())):
print ( * each_row, " " )
|
Output
NAME AGE COURSE
Samuel 21 Data Structures
Richie 20 Machine Learning
Lauren 21 OOPS with Java
Share your thoughts in the comments
Please Login to comment...