【问题标题】:Another Dictionary, Another Format Output另一个字典,另一种格式输出
【发布时间】:2015-01-31 02:01:56
【问题描述】:

我正在处理 Python 嵌套字典。我有一本字典;

contacts = {
            'name4': {'x': 5, 'y': 2, 'z': 7}, 
            'Name2': {'x': 5, 'y': 2, 'z': 5}, 
            'name3': {'x': 5, 'y': 2, 'z': 7}, 
            'Name1': {'x': 5, 'y': 2, 'z': 7}
           }

我需要一个循环来返回将嵌套字典排序为 2 列的字典。显然,我必须使用的确切间距。只有嵌套字典上返回的值,因为我有一个标题来显示每个值的含义。 我想要的输出是这样的;

姓名4........5........2........7                         姓名3........5........2 ........7
Name2........5........2........7                        Name1........5........2.... .....7

【问题讨论】:

  • 按什么排序?我想你的意思是你只想在多列中显示数据?
  • @justderb 只要嵌套数据保持在一起,我不在乎哪个人和他们的数据在哪里或在什么列中。

标签: python loops dictionary output


【解决方案1】:

尝试这种索引检查技术,您可以在其中添加'\t''\n'

string = ''

for i in range(len(contacts.items())):
    string += contacts.items()[i][0] + ': '
    string += ' '.join([str(j) for j in contacts.items()[i][1].values()])

    if i % 2 == 0:
        string += '\t'

    if i % 2 != 0:
        string += '\n'

print string # prints in two columns

【讨论】:

  • 有没有办法截断名字?我一直在调整 name 键的大小,我不介意将其缩小到 15 个字符的限制。
猜你喜欢
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
相关资源
最近更新 更多