Python dict到用户格式字符串



转换Python dict的最简单方法是什么,例如:

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

使用用户格式转换为字符串,例如:

'%s - %sn'

所以它给了我:

a - value
b - another_value

这是有效的,但也许有一些更短/更好的东西使用地图(不迭代收集)

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

我会把它写成:

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

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

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

既然您询问的是map,这里有一种使用map:编写它的方法

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

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

最新更新