简体   繁体   English

通过打印打印字典

[英]Printing a dictionary with print

Why does 为什么

 d = {"A":10,"B":20}
 print(*d, sep=" ")

Output AB and not 10 20 ? 输出AB而不是10 20

And how do i get 10 20 ? 我怎么得到10 20

Assuming what you want is to print the keys together with the values you could use a generator expression: 假设您想要将键和值一起打印,则可以使用生成器表达式:

print(' '.join('{}={}'.format(k,v) for k,v in d.items()))

or if you prefer to keep the sep argument instead of using str.join : 或者,如果您希望保留sep参数而不是使用str.join

print(*('{}={}'.format(k,v) for k,v in d.items()),sep=' ')

both with output: 两者都有输出:

A=10 B=20

简单地写

print (*d.values() )

Please see a demo for print introduction: 请查看演示的印刷介绍:

>>> def demo(p, *args, **kwargs):
...     print(args)
...     print(kwargs)
...
>>> demo(0, 1, 2, 3, 4, callback='demo_callback')
(1, 2, 3, 4)
{'callback': 'demo_callback'}
  1. The * syntax requires a tuple/list; *语法需要一个元组/列表;

  2. The ** syntax requires a dictionary; **语法需要字典; each key-value pair in the dictionary becomes a keyword argument. 字典中的每个键值对都将成为关键字参数。

print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False) print(* objects,sep ='',end ='\\ n',file = sys.stdout,flush = False)

Print objects to the text stream file, separated by sep and followed by end. 将对象打印到文本流文件中,以sep分隔,然后以end分隔。 sep, end and file, if present, must be given as keyword arguments. sep,end和file(如果存在)必须作为关键字参数给出。

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. 所有非关键字参数都将像str()一样转换为字符串,并写入流中,以sep分隔,然后以end分隔。 Both sep and end must be strings; sep和end都必须是字符串; they can also be None, which means to use the default values. 它们也可以是None,这意味着要使用默认值。 If no objects are given, print() will just write end. 如果没有给出对象,print()只会写完。

The file argument must be an object with a write(string) method; file参数必须是带有write(string)方法的对象; if it is not present or None, sys.stdout will be used. 如果不存在或没有,将使用sys.stdout。 Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. 由于打印的参数会转换为文本字符串,因此print()不能与二进制模式文件对象一起使用。 For these, use file.write(...) instead. 对于这些,请改用file.write(...)。

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed. 通常是否由文件决定是否对输出进行缓冲,但是如果flush关键字参数为true,则将强制刷新流。

>>> print(d, sep=" ")
{'B': 20, 'A': 10}
>>> print(*d, sep=" ")
B A
>>> print(**d, sep=" ")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'B' is an invalid keyword argument for this function

This is a valid way: 这是一种有效的方法:

>>> print(*d.values(), sep=" ")

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

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