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

[![enter image description here](https://i.stack.imgur.com/F6j09.png)](https://i.stack.imgur.com/F6j09.png)

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

Answer: 
You can easily filter your dictionary to save only the top two values by sorting and slicing.

```py
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:

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

```

Then You can do *anything* you want with your data.

---

If you're comfortable using an external package [tabulate](https://pypi.org/project/tabulate/) is a great option.

```py
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:

```py
# 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])

```