Reputation: 287
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?
Upvotes: 0
Views: 1375
Reputation: 35636
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
Upvotes: 1
Reputation: 392
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])
Upvotes: 0