[英]Convert a dictionary to a table with column names using base Python without Pandas
您可以通过排序和切片轻松过滤字典以仅保存前两个值。
heights = {'Brenda': 155, 'Cindy': 130, 'Andy': 150}
# Sort Data and Keep Top 2 Results
top_two_heights = sorted(heights.items(), key=lambda v: -v[1])[:2]
print(top_two_heights)
Output:
[('Brenda', 155), ('Andy', 150)]
然后你可以对你的数据做任何你想做的事情。
如果您对使用外部 package 感到满意,那么表格是一个不错的选择。
from tabulate import tabulate
# Header Labels
header_labels = ('Name', 'Height')
heights = {'Andy':150, 'Brenda':155, 'Cindy':130}
# Sort Data and Keep Top 2 Results
top_two_heights = sorted(heights.items(), key=lambda v: -v[1])[:2]
# Use Tabulate to Build Table
print(tabulate(top_two_heights, headers=header_labels, tablefmt='grid'))
Output:
+--------+----------+
| Name | Height |
+========+==========+
| Brenda | 155 |
+--------+----------+
| Andy | 150 |
+--------+----------+
如果你不想导入,你可以循环并打印出值:
# Header Labels
header_labels = ('Name', 'Height')
heights = {'Andy': 150, 'Brenda': 155, 'Cindy': 130}
# Sort Data and Keep Top 2 Results
top_two_heights = sorted(heights.items(), key=lambda v: -v[1])[:2]
fmt_str = '{:^10}|{:^10}'
print(fmt_str.format(*header_labels))
print('-' * 20)
for (a, b) in top_two_heights:
print(fmt_str.format(a, b))
Output:
Name | Height
--------------------
Brenda | 155
Andy | 150
您可以将字典转换为 CSV 文件,这将为您提供所需的 output。
import csv
heights = {'Andy':150, 'Brenda':155, 'Cindy':130}
last_key = "Cindy"
with open("filename.csv", "w") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Name", "Height"])
for key, value in heights.items():
if key == last_key:
break
else:
writer.writerow([key, value])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.