简体   繁体   English

使用没有 Pandas 的基本 Python 将字典转换为具有列名的表

[英]Convert a dictionary to a table with column names using base Python without Pandas

I have a dictionary that looks like this:我有一本看起来像这样的字典:

heights = {'Andy':150, 'Brenda':155, 'Cindy':130}高度 = {“安迪”:150,“布伦达”:155,“辛迪”:130}

I want a table with one column of names and one column of heights.我想要一张包含一列名称和一列高度的表格。 I want to keep only the top 2 heights.我只想保留前 2 个高度。 The end result should look like this:最终结果应如下所示:

在此处输入图像描述

Is there a relatively easy way to get such a table in base Python without using Pandas ?有没有一种相对简单的方法可以在不使用 Pandas的情况下在基础 Python 中获得这样的表?

You can easily filter your dictionary to save only the top two values by sorting and slicing.您可以通过排序和切片轻松过滤字典以仅保存前两个值。

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

[('Brenda', 155), ('Andy', 150)]

Then You can do anything you want with your data.然后你可以对你的数据做任何你想做的事情。


If you're comfortable using an external package tabulate is a great option.如果您对使用外部 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: Output:

+--------+----------+
| Name   |   Height |
+========+==========+
| Brenda |      155 |
+--------+----------+
| Andy   |      150 |
+--------+----------+

If you wanted no imports you could just loop over and print out the values:如果你不想导入,你可以循环并打印出值:

# 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: Output:

   Name   |  Height  
--------------------
  Brenda  |   155    
   Andy   |   150    

You could convert the dictionary to a CSV file, which would give you the desired output.您可以将字典转换为 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM