How To Print Aligned Dictionary Python” is a useful concept because sometimes we want a dictionary to represent data in tabular format. It gives a similar user interface which is provided in the table representation.
Here we are going to cover various methods to align dictionary data in table format.
The first method is using tab with fixed spacing to align dictionary items.
In the second method, initially, we are taking padding .We calculate the maximum length of the key. We sum up padding with maximum length and then use it as space.
Hence, the dictionary will print data in tabular format.
01. Example
Marks = { "Mathematics": 90, "Chemistry": 90, "Physics": 97, "English": 95, "Computer Science": 99 } for key, value in Marks.items(): print(f'{key:20}{value}')
Output:
02. Example
- Find max length of dictonary key.
- Decide padding size(Optional)
- Define total space required (space = length + padding)
- Now print the dictonary values with keys.
Marks = { "Mathematics": 90, "Chemistry": 90, "Physics": 97, "English": 95, "Computer Science": 99 } length = max(len(x) for x in Marks) # decide padding padding = 5 #Calculate Total Space required space = length + padding #Finally print the statements for key, value in Marks.items(): subject = "{0:{space}}".format(key, space=space) result = "{0:5d}".format(value) print(subject + result)
Output: