使用格式化方法打印字典内容

Printing dictionary contents using format method

我刚开始学习python并尝试使用格式功能打印字典内容。我在阅读 https://www.python-course.eu/python3_formatted_output.php

时获得了一些见解

问题 1:double * 运算符用于执行指数计算,它与字典的关系如何?

问题 2:对于这段代码,我得到 IndexError: tuple index out of range。我一定是误解了什么。

students = {100 : "Udit", 101 : "Rohan", 102 : "Akash", 103 : "Rajul"}
for student in students :
    format_string = str(student) + ": {" + str(student) + "}"
    print(format_string)
    print(format_string.format(**students))

你这样迭代:

for student in students :

因为 students 是一个字典,所以这会遍历键,这些键是数字,比如 100,这意味着最终构建这样的格式字符串:

'100: {100}'

然后,当您对其调用 format 时,100 要求位置参数 #100。但是你只传递了 0。所以你得到一个 IndexError.

只有当字典键是有效的字符串格式键时,您才能有效地使用 format(**students) 语法。


与此同时,我不知道是谁在传播 format(**d) 是个好主意的想法。如果你只想使用 dict 或其他映射来格式化,这就是在 3.2 中添加 format_map 的目的:

print(format_string.format_map(students))

一个好处是,当你做错了什么时,你会得到更有用的错误信息:

ValueError: Format string contains positional fields

当您看到它时,您可以打印出格式字符串本身并看到 {100},是的,那是一个位置字段。需要更少的调试。

更重要的是,没有关键字拼写更易于阅读和理解。而且它甚至更高效(3.6 中的效率不如 3.2 中的效率,但 format 仍然需要构建一个新的字典副本,而 format_map 可以使用你给它的任何映射 as-is) .


最后,像这样动态构建格式字符串很少是个好主意。打印您要打印的内容的一种更简单的方法是:

for num, student in students.items():
    print(f'{num}: {student}')

或者,如果您不使用 3.6,或者只是想明确使用 formatformat_map 而不是 f-strings,同样的想法。