Print a dictionary into a table

前端 未结 6 1668
伪装坚强ぢ
伪装坚强ぢ 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条回答
  • 2020-12-18 07:26

    You can do it directly as in

    >>> print("Name\tAge")
    Name  Age
    >>> for i in dic:
    ...     print("{}\t{}".format(i,dic[i]))
    ... 
    Tim 3
    Kate    2
    >>> 
    

    It displays even better if executed as a script

    Name    Age
    Tim     3
    Kate    2
    

    And for the other representation

    lst = [{'Name':'Tim', 'Age':3}, {'Name':'Kate', 'Age':2}]
    print("Name\tAge")
    for i in lst:
        print("{}\t{}".format(i['Name'],i['Age']))
    

    And for your final question - Is it a good way to first convert them into a list of dictionaries Answer is No, A dictionary is hashed and provides faster access than lists

    0 讨论(0)
  • 2020-12-18 07:26

    You can do it this way,

    format = "{:<10}{:<10}"    
        print format.format("Name","Age")
        for name,age in dic.iteritems():
           print format.format(name,age)
    

    I have written a simple library to pretty print dictionary as a table https://github.com/varadchoudhari/Neat-Dictionary which uses a similar implementation

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-18 07:42

    Well, you don't have to convert it in a dictionary, you can directly:

    print('Name Age')
    for name, age in dic.items():
        print('{} {}'.format(name, age))
    
    0 讨论(0)
  • 2020-12-18 07:44

    You could use pandas.

    In [15]: import pandas as pd
    
    In [16]: df = pd.DataFrame({'Tim':3, 'Kate':2}.items(), columns=["name", "age"]) 
    
    In [17]: df
    Out[17]: 
       name  age
    0   Tim    3
    1  Kate    2
    
    0 讨论(0)
  • 2020-12-18 07:46

    Iterate dictionary and print every item.

    Demo:

    >>> dic = {'Tim':3, 'Kate':2}
    >>> print "Name\tAge"
    Name    Age
    >>> for i in dic.items():
    ...    print "%s\t%s"%(i[0], i[1])
    ... 
    Tim 3
    Kate    2
    >>> 
    

    By CSV module

    >>> import csv
    >>> dic = {'Tim':3, 'Kate':2}
    >>> with open("output.csv", 'wb') as fp:
    ...     root = csv.writer(fp, delimiter='\t')
    ...     root.writerow(["Name", "Age"])
    ...     for i,j in dic.items():
    ...         root.writerow([i, j])
    ... 
    >>> 
    

    Output: output.csv file content

    Name    Age
    Tim     3
    Kate    2
    

    We can use root.writerows(dic.items()) also

    0 讨论(0)
提交回复
热议问题