8
Student_Name = {"Mathematics": 90, 
                "Computer Science": 100, 
                "Chemistry": 90, 
                "Physics": 97, 
                "English": 95}
for key,value in Student_Name.items():
    print(key,value)

I want to print like:

Mathematics        90
Computer Science   100
Chemistry          90 

and so on but it is printing like this

Mathematics 90
Computer Science 100
Chemistry 90
Physics 97
English 95

I want to print marks and subjects in proper line.

Georgy
  • 12,464
  • 7
  • 65
  • 73
Silver fang
  • 109
  • 1
  • 3

3 Answers3

7

You've got a number of options:

Taking your original code you could simply tab the next item along:

for key, value in Student_Name.items():
    print(key,'\t',value)

Although this wouldn't be perfect as it's a tab, and unless all the keys are similar length it wouldn't look as you intended.

Output:

Mathematics      90
Computer Science         100
Chemistry        90
Physics          97
English          95

A better solution could would be:

for key, value in Student_Name.items():
    print(f'{key:20}{value}')

output:

Mathematics         90
Computer Science    100
Chemistry           90
Physics             97
English             95

Python 3.6 required

My only question to you is why, you want to do this and would it be better to print some file and use delimiter and worry about presentation later. Either way you should be able to do with the above

Equally suitable would be the 1st answer here

for key,value in Student_Name.items():
...     print("{0:20}{1:5d}".format(key,value))

Which out puts the same as f' but, both have the problem that if the subject key is much longer than the others the appearance will need to be amended. Changing key {key:20} or {0:20} to a greater number will help, but maybe you could count check the length of your keys using the longest as the value here plus 5 for padding.

for example you could do this (added in an extra key for illustration purposes:

 Student_Name = {"Mathematics": 90, "Computer Science": 100, "Chemistry": 90, "Physics": 97, "English": 95, "REALLY LONG SUBJECT ABOUT POLITICS": 10}
 # Get the longest subject name
 length = max(len(x) for x in Student_Name)
 # decide on padding
 padding = 5

 #use these two value to working out the exact space required
 space = length + padding

 #format and print the statement
 for key, value in Student_Name.items():
 ...     subject = "{0:{space}}".format(key, space=space)
 ...     result = "{0:5d}".format(value)
 ...     print(subject + result)

Output :

Mathematics                           90
Computer Science                     100
Chemistry                             90
Physics                               97
English                               95
REALLY LONG SUBJECT ABOUT POLITICS    10

Would always make the result the right distance away from the longest subject name.

AppHandwerker
  • 1,758
  • 12
  • 22
  • 2
    You can also do the longest subject name length like so `length = max(map(len,Student_Name))`. Map function is really useful for operations on all elements in an iterable. – scotty3785 Feb 07 '19 at 13:45
1

Try this:

>>> for key,value in Student_Name.items():
...     print("{0:20}{1:5d}".format(key,value))

Beginning from python 3.6, you can use this also. (Courtesy of Jon Clements)

for key,value in Student_Name.items():
    print(f'{key:20}{value}')

For additional references, visit this link.

taurus05
  • 2,491
  • 15
  • 28
1

In order to avoid hardcoded width of the first column as in other answers, you can calculate the maximum key length in advance.

Simple example:

grades = {"Mathematics": 90, 
          "Computer Science": 100, 
          "Chemistry": 90, 
          "Physics": 97, 
          "English": 95}
max_key_len = max(map(len, grades))
format_string = '{{key:{}}}  {{value}}'.format(max_key_len)
for key, value in grades.items():
    print(format_string.format(key=key, value=value))

will print:

Mathematics       90
Computer Science  100
Chemistry         90
Physics           97
English           95

We can improve the code further by wrapping it in a function and adding a separator parameter:

from typing import Dict, Iterator


def to_aligned_records(dict_: Dict,
                       *,
                       sep: str = ' ') -> Iterator[str]:
    """Yields key-value pairs as strings that will be aligned when printed"""
    max_key_len = max(map(len, dict_))
    format_string = '{{key:{max_len}}}{sep}{{value}}'.format(max_len=max_key_len, sep=sep)
    for key, value in dict_.items():
        yield format_string.format(key=key, value=value)

And use it like this:

>>> print(*to_aligned_records(grades), sep='\n')
Mathematics      90
Computer Science 100
Chemistry        90
Physics          97
English          95

>>> print(*to_aligned_records(grades, sep=' '*4), sep='\n')
Mathematics         90
Computer Science    100
Chemistry           90
Physics             97
English             95

>>> print(*to_aligned_records(grades, sep='\t'), sep='\n')
Mathematics         90
Computer Science    100
Chemistry           90
Physics             97
English             95
Georgy
  • 12,464
  • 7
  • 65
  • 73