简体   繁体   中英

Printing a dictionary with print

Why does

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

Output AB and not 10 20 ?

And how do i get 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 :

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 to the text stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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