Print a dictionary into a table

前端 未结 6 1803
伪装坚强ぢ
伪装坚强ぢ 2020-12-18 06:46

I have a dictionary:

dic={\'Tim\':3, \'Kate\':2}

I would like to output it as:

Name Age
Tim 3
Kate 2

Is i

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-18 07:27

    If you go for higher numbers, then having number in the first column is usually a safer bet as you never know how long a name can be.

    Given python3:

    dic={'Foo':1234, 'Bar':5, 'Baz':123467}
    

    This:

    print("Count".rjust(9), "Name")
    rint("\n".join(f'{v:9,} {k}' for k,v in dic.items()))
    

    Prints

        Count Name
        1,234 Foo
            5 Bar
      123,467 Baz
    

提交回复
热议问题