如何将字典的键值对打印为对齐表? [英] How to print key-value pairs of a dict as an aligned table?
问题描述
Student_Name = {"Mathematics": 90,
"Computer Science": 100,
"Chemistry": 90,
"Physics": 97,
"English": 95}
for key,value in Student_Name.items():
print(key,value)
我要像这样打印:
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.
推荐答案
您有很多选择:
使用原始代码,您只需将下一项跳到以下位置即可:
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.
输出:
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}')
输出:
Mathematics 90
Computer Science 100
Chemistry 90
Physics 97
English 95
需要Python 3.6
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))
输出与f'相同,但是都存在以下问题:如果主题 key
比其他主题长得多,则需要修改外观.将键 {key:20}
或 {0:20}
更改为更大的数字会有所帮助,但也许您可以使用最长的密钥来计算密钥的长度.此处的值加上5用于填充.
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)
输出:
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.
这篇关于如何将字典的键值对打印为对齐表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!