【发布时间】:2021-04-19 15:56:55
【问题描述】:
我想使用.format() 以某种格式打印嵌套字典(请参阅下面的预期输出)。
应该是:
- 按字母顺序排序(按名称,我设法做到了)
- 列宽应该是最长项目的宽度加上 3 个空格(我没能做到)
有问题的字典:
data = {"Kevin H": {"street":"Maple Street 13", "phone": "01234567"},
"Stewart Bob": {"street":"Agave Street 124", "phone": "76543210"},
"John Paul": {"street":"Old Town Road 1", "phone": "09876543"}}
预期输出:
John Paul Old Town Road 1 09876543
Kevin H Maple Street 13 01234567
Stewart Bob Agave Street 124 76543210
到目前为止,我有:
sorted_data = dict(sorted(data.items()))
for name, info in sorted_data.items():
print("{} {} {}".format(name, info["street"],info["phone"]))
所以,我的问题是:如何使每列的宽度等于最长字符串(在该列中)的长度加上 3 个空格?
【问题讨论】:
标签: python python-3.x dictionary