【问题标题】:.format() nested dictionary with specific width for each column.format() 嵌套字典,每列具有特定宽度
【发布时间】: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


    【解决方案1】:

    这是一个使用函数式方法的解决方案。

    1. 获取您感兴趣的列:
    >>> columns = sorted((k, v['street'], v['phone']) for k, v in contact.items())
    >>> columns
    [('John Paul', 'Old Town Road 1', '09876543'),
     ('Kevin H', 'Maple Street 13', '01234567'),
     ('Stewart Bob', 'Agave Street 124', '76543210')]
    
    1. 获取每个字符串的长度:
    >>> lengths = map(lambda x: list(map(len, x)), columns)
    >>> list(lengths)
    [[7, 15, 8], [11, 16, 8], [9, 15, 8]]
    
    1. 获取每列的最大值。方便transpose the array获取每一行的最大值:
    >>> lengths = map(list, zip(*lengths))
    >>> max_lengths = map(max, lengths)
    >>> list(max_lengths)
    [11, 16, 8]
    
    1. 使用variable within the format specifier 打印数据以指示字段宽度:
    >>> PAD = 3
    >>> max_lengths = [x+PAD for x in max_lengths]
    >>> for row in columns:
            print("{:{name_w}} {:{street_w}} {:{code_w}}".format(*row, 
                name_w=max_lengths[0], street_w=max_lengths[1], code_w=max_lengths[2]))
    John Paul      Old Town Road 1     09876543
    Kevin H        Maple Street 13     01234567
    Stewart Bob    Agave Street 124    76543210
    

    【讨论】:

      【解决方案2】:

      在遍历项目之前,您必须以某种方式获取每列的最大宽度,如下所示:

      contacts = {
          "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"}
      }
      
      # Collect all widths for each columns
      name_widths = [len(x) for x in contacts]
      street_widths = [len(contacts[x]['street']) for x in contacts]
      phone_widths = [len(contacts[x]['phone']) for x in contacts]
      
      # Sort contacts
      sorted_contacts = dict(sorted(contacts.items()))
      
      for name, info in sorted_contacts.items():
          print('{} {} {}'.format(
              name.ljust(max(name_widths) + 3),
              info['street'].ljust(max(street_widths) + 3),
              info['phone'].ljust(max(phone_widths) + 3)
          ))
      

      完成后,只需使用内置的字符串方法进行对齐即可。

      【讨论】:

        猜你喜欢
        • 2018-09-28
        • 1970-01-01
        • 2020-02-29
        • 1970-01-01
        • 2012-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-08
        相关资源
        最近更新 更多