我希望以一种干净的可读格式打印嵌套字典。我已经完成了打印字典键及其值的标准方法,但由于这是嵌套的,因此它不能很好地呈现。有人可以解释我如何实现以下格式化吗?
Host Port Service
192.168.1.200 80 IIS 7.5
443 IIS 7.5
192.168.1.201 22 SSHv.199
字典示例
192.168.1.200 {'3389': 'Microsoft Terminal Service', '49160': 'Microsoft Windows RPC', '49163': 'Microsoft Windows RPC', '135': 'Microsoft Windows RPC', '49152': 'Microsoft Windows RPC', '49153': 'Microsoft Windows RPC'}
答案 0 :(得分:3)
您可以使用json.dumps
格式化选项:
>>> d={'server1':{'3389': 'Microsoft Terminal Service', '49160': 'Microsoft Windows RPC', '49163': 'Microsoft Windows RPC', '135': 'Microsoft Windows RPC', '49152': 'Microsoft Windows RPC', '49153':'Microsoft Windows RPC'},'server2':{'morekeys':'morevalues'}}
>>> print json.dumps(d, indent=4)
{
"server1": {
"3389": "Microsoft Terminal Service",
"49160": "Microsoft Windows RPC",
"49163": "Microsoft Windows RPC",
"135": "Microsoft Windows RPC",
"49152": "Microsoft Windows RPC",
"49153": "Microsoft Windows RPC"
},
"server2": {
"morekeys": "morevalues"
}
}