Python3:如何对齐字典中值的格式化输出?

问题描述 投票:0回答:2

我熟悉 Python3 中的位置参数格式化。 例如:

D = { '姓名' : '鲍勃', '状态' : '全职' } print( '"{0:<8}" "{1:>20}"'.format( D[ '名称' ], D[ '状态' ] ) ) “鲍勃”“充分就业”

我想做的是使用字典键来确定哪个值应该对齐显示。

有没有简单的方法可以做到这一点?

我已经尝试过这个,但我一定错过了一些东西。

print( '"{'名称':<8} "{'status':>20}"'.format( **D ) ) 回溯(最近一次调用最后一次): 文件“”,第 1 行,位于 关键错误:“'名称'”

python-3.x string dictionary formatting key
2个回答
0
投票

你可以尝试:

print('"{0[name]:8}"  "{0[status]:>20}"'.format(D))

输出:

"Bob     "  "      Fully Employed" 

0
投票

您可以简单地使用

str.format
中的按键名称:

D = {"name": "Bob", "status": "Fully Employed"}
print('"{name:<8}" "{status:>20}"'.format(**D))

打印:

"Bob     " "      Fully Employed"
© www.soinside.com 2019 - 2024. All rights reserved.