简体   繁体   English

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

[英]Printing dictionary contents using format method

I just started learning python and tried printing the dictionary contents using format function. 我刚开始学习python,并尝试使用format函数打印字典内容。 I gained some insight while reading https://www.python-course.eu/python3_formatted_output.php 我在阅读https://www.python-course.eu/python3_formatted_output.php时获得了一些见识

Question 1 : The double * operator is used performing exponential calculations, how it behaves with the dictionaries? 问题1:double *运算符用于执行指数计算,它与字典的行为如何?

Question 2 : For this block of code I am getting IndexError: tuple index out of range . 问题2:对于此代码块,我得到IndexError: tuple index out of range I must have misinterpreted something. 我一定误解了一些东西。

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))

You iterate like this: 您这样迭代:

for student in students :

Since students is a dict, this iterates over the keys, which are numbers, like 100 , which means end up building a format string like this: 由于students是字典,因此会遍历数字之类的键,例如100 ,这意味着最终要构建如下格式的字符串:

'100: {100}'

And then, when you call format on that, the 100 is asking for positional argument #100. 然后,当您调用format时, 100要求输入位置参数#100。 But you only passed 0. So you get an IndexError . 但是您只传递了0。因此,您得到了IndexError

You can only usefully use the format(**students) syntax when the dict keys are valid string format keys. 当dict键是有效的字符串格式键时,您只能有用地使用format(**students)语法。


Meanwhile, I don't know who's been spreading the idea that format(**d) is a great idea. 同时,我不知道谁一直在传播format(**d)是个好主意。 If you want to format using only a dict or other mapping, that's what format_map was added for, back in 3.2: 如果您只想使用字典或其他映射进行格式化,那就是在3.2中添加了format_map目的:

print(format_string.format_map(students))

One advantage is that when you do something wrong, you get a more useful error message: 一个优点是,当您做错了什么时,您会收到一条更有用的错误消息:

ValueError: Format string contains positional fields

When you see that, you can print out the format string itself and see that {100} , and, yep, that's a positional field. 看到它时,您可以打印出格式字符串本身,并看到{100} ,是的,这是一个位置字段。 Much less debugging needed. 所需的调试少得多。

More importantly, it's simpler to read and understand without the keyword splatting. 更重要的是,它无需关键字喷溅即可轻松阅读和理解。 And it's even more efficient (not as much so in 3.6 as in 3.2, but format still has to build a new dict copy, while format_map can use whatever mapping you give it as-is). 而且它甚至更有效(在3.6中不如在3.2中那么高,但是format仍然必须建立一个新的dict副本,而format_map可以使用您format_map原样使用的任何映射)。


Finally, building a format string dynamically like this is rarely a good idea. 最后,像这样动态地构建格式字符串很少是一个好主意。 A much simpler way to print what you're trying to print is: 打印您要打印的内容的一种简单得多的方法是:

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

Or, if you're not using 3.6, or just want to use format or format_map explicitly instead of f-strings, same idea. 或者,如果您不使用3.6,或者只是想显式地使用formatformat_map而不是f字符串,则具有相同的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM