Python如何在一行中打印字典?

yus*_*426 4 python printing dictionary python-2.7

嗨,我是Python的新手,我正在努力打算如何打印字典.

我有一本字典,如下所示.

dictionary = {a:1,b:1,c:2}
Run Code Online (Sandbox Code Playgroud)

如何在一行中打印字典,如下所示?

a1b1c2
Run Code Online (Sandbox Code Playgroud)

我想在一行中打印键和值,但我自己也想不通.

我很感激你的意见!

PyN*_*oob 9

用字典,例如

dictionary = {'a':1,'b':1,'c':2}
Run Code Online (Sandbox Code Playgroud)

你可以尝试:

print ''.join(['{0}{1}'.format(k, v) for k,v in dictionary.iteritems()])
Run Code Online (Sandbox Code Playgroud)

导致

a1c2b1

如果订单的问题,尝试使用OrderedDict,如由职位.


Bra*_*ell 6

如果你想要一个字符串包含答案,你可以这样做:

>>> dictionary = {'a':1,'b':1,'c':2}
>>> result = "".join(str(key) + str(value) for key, value in dictionary.items())
>>> print(result)
c2b1a1
Run Code Online (Sandbox Code Playgroud)

这对空字符串使用 join 方法。字典没有排序,因此输出的顺序可能会有所不同。

更新- 使用 f-strings 你也可以这样做:

>>> result = "".join(f"{key}{value}" for key, value in dictionary.items())
Run Code Online (Sandbox Code Playgroud)