简体   繁体   中英

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}

I want a table with one column of names and one column of heights. I want to keep only the top 2 heights. The end result should look like this:

在此处输入图像描述

Is there a relatively easy way to get such a table in base Python without using Pandas ?

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:

[('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.

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

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:

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

You could convert the dictionary to a CSV file, which would give you the desired 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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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