![](/img/trans.png)
[英]Convert list of string dictionary to another dictionary using python 2.7 and print in tabular format
[英]Python print list in tabular format
如何以表格格式打印字典中存在的列表中的項目?
print('{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote'))
print("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
我正在使用上面的代碼並像這樣得到 output 。 我還在 output 的第一行打印了一個字典。
您也可以'{:>0}{:>10}{:>10}{:>20}'
打印帶有值的行。
'{:>0}{:>10}{:>10}{:>20}'.format(key, *value)
您甚至可以將模式分配給變量以簡單地替換它
dct = {1: ['ankit', 32, 37], 2:['asfkjld', 54, 62]}
pattern = '{:>0}{:>10}{:>10}{:>20}'
print(pattern.format('ID','Name','Votes','% of Total Vote'))
for key, value in dct.items():
print(pattern.format(key, *value))
結果:
ID Name Votes % of Total Vote
1 ankit 32 37
2 asfkjld 54 62
對於更復雜的事情,您可以使用特殊模塊。
或者您可以將其保留為pandas.DataFrame
,因為它具有許多有用的功能。
import pandas as pd
import matplotlib.pyplot as plt
dct = {1: ['ankit', 32, 37], 2:['asfkjld', 54, 62]}
df = pd.DataFrame.from_dict(dct, orient='index')
df.columns = ['Name','Votes','% of Total Vote']
# --- display text ---
print(df)
print('---')
print('Total Votes:', df['Votes'].sum())
print('Total % :', df['% of Total Vote'].sum())
# --- display plot ---
df.plot.bar(x='Name')
plt.show()
結果:
Name Votes % of Total Vote
1 ankit 32 37
2 asfkjld 54 62
---
Total Votes: 86
Total % : 99
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.