How to print a dictionary in tabular form and alphabetically?

user4758796 picture user4758796 · Apr 15, 2015 · Viewed 9.9k times · Source

I have a dictionary and wish to print in tabular form with the first header as "code" and second as "name" and then sorted alphabetically.

i have currently:

 import json
 q = my_dict() #which is the dictionary
 d = json.dumps(q)
 print(d)

output:

"GEL": "Georgian Lari",
"BOB": "Bolivian Boliviano",
"ZAR": "South African Rand",

Which is the wrong way round and i am not sure how to insert columns titles. Sorting by Alphabetical order would also help me a lot!

Name                   Code
"Bolivian Boliviano"   "BOB"
"Georgian Lari"        "GEL"
"South African Rand"   "Zar"

Something like this is what im looking for.

Answer

Adam Smith picture Adam Smith · Apr 15, 2015

If third-party modules are an option, you can use tabulate.

Run this from the command line:

$ pip install tabulate

Then in your script

from tabulate import tabulate

headers = ['Name', 'Code']
data = sorted([(v,k) for k,v in d.items()]) # flip the code and name and sort
print(tabulate(data, headers=headers))

That will give you the output

Name                Code
------------------  ------
Bolivian Boliviano  BOB
Georgian Lari       GEL
South African Rand  ZAR