Skip to main content
 首页 » 编程设计

Python dict 到用户格式字符串

2025年05月04日16pander-it

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

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

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

'%s - %s\n' 

所以它给了我:

a - value 
b - another_value 

这行得通,但使用 map 可能会更短/更好(无需遍历集合)

''.join(['%s %s\n' % 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