Python dict到用户格式字符串

时间:2012-01-17 11:52:02

标签: python string join dictionary

转换Python dict的最简单方法是:

a = {'a': 'value', 'b': 'another_value', ...}

使用用户格式输入字符串,例如:

'%s - %s\n'

所以它给了我:

a - value
b - another_value

这样可行,但也许使用地图更短/更好(没有迭代收集)

''.join(['%s %s\n' % o for o in a.items()])

2 个答案:

答案 0 :(得分:5)

我写这个:

>>> print '\n'.join(' '.join(o) for o in a.items())
a value
b another_value

或者:

>>> print '\n'.join(map(' '.join, a.items()))
a value
b another_value

答案 1 :(得分:2)

您可以省略方括号以避免构建中间列表:

''.join('%s %s\n' % o for o in a.items())

由于您询问map,以下是使用map撰写文章的一种方法:

''.join(map(lambda o:'%s %s\n' % o, a.items()))

这是一个偏好问题,但我个人觉得它比原始版本更难阅读。

相关问题