Print a dictionary into a table

前端 未结 6 1804
伪装坚强ぢ
伪装坚强ぢ 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

提交回复
热议问题