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

时间:2018-03-21 04:56:06

标签: python dictionary string-formatting

我刚开始学习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))

1 个答案:

答案 0 :(得分:3)

你这样迭代:

for student in students :

由于students是一个dict,它会遍历键,这些数字是100,这意味着最终会构建一个这样的格式字符串:

'100: {100}'

然后,当你打电话给format时,100要求位置参数#100。但你只通过0.所以你得到IndexError

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

与此同时,我不知道是谁传播了format(**d)是个好主意的想法。如果你想仅使用dict或其他映射进行格式化,那就是添加format_map的内容,回到3.2:

print(format_string.format_map(students))

一个优点是,当您做错事时,您会收到更有用的错误消息:

ValueError: Format string contains positional fields

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

更重要的是,如果没有关键字splatting,它的阅读和理解会更简单。它的效率更高(3.6中的效率不如3.2,但format仍然需要构建一个新的dict副本,而format_map可以使用你给它的任何映射。“ / p>

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

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

或者,如果你没有使用3.6,或者只是想明确地使用formatformat_map而不是f-strings,那就是同样的想法。