Python 将字典打印到表格中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29265002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:17:30  来源:igfitidea点击:

Print a dictionary into a table

pythonpython-2.7dictionary

提问by Tim

I have a dictionary:

我有一本字典:

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

I would like to output it as:

我想将其输出为:

Name Age
Tim 3
Kate 2

Is it a good way to first convert them into a list of dictionaries,

首先将它们转换为字典列表的好方法

lst = [{'Name':'Tim', 'Age':3}, {'Name':'Kate', 'Age':2}]

and then write them into a table, by the method in https://stackoverflow.com/a/10373268/156458?

然后通过https://stackoverflow.com/a/10373268/156458中的方法将它们写入表格?

Or is there a way better in some sense?

或者在某种意义上有更好的方法吗?

采纳答案by Francis Colas

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))

回答by Bhargav Rao

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 dictionariesAnswer is No, A dictionary is hashed and provides faster access than lists

对于您的最后一个问题 -首先将它们转换为字典列表是一种好方法吗答案是否定的,字典经过哈希处理并提供比列表更快的访问

回答by Akavall

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

回答by Vivek Sable

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

通过 CSV 模块

>>> 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

输出:output.csv 文件内容

Name    Age
Tim     3
Kate    2

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

我们可以用root.writerows(dic.items())同样

回答by vardos

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-Dictionarywhich uses a similar implementation

我写了一个简单的库来漂亮地打印字典作为表格 https://github.com/varadchoudhari/Neat-Dictionary使用类似的实现