user4758796
user4758796

Reputation:

How to print a dictionary in tabular form and alphabetically?

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.

Upvotes: 4

Views: 11844

Answers (3)

oaksandbrooms
oaksandbrooms

Reputation: 91

Here is how I would do it:

import pandas as pd

pd.DataFrame(d)

Upvotes: 1

Adam Smith
Adam Smith

Reputation: 54173

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

Upvotes: 9

xnx
xnx

Reputation: 25508

I'm not sure if you need the quotes, but you can print your dictionary in the order you want with:

max_len = max([len(v) for v in d.values()])
padding = 4
for k,v in sorted(d.items(), key=lambda i:i[1]):
    print('{v:{v_len:d}s} {k:3s}'.format(v_len=max_len+padding,
                                           v=v, k=k))

Output:

Bolivian Boliviano     BOB
Georgian Lari          GEL
South African Rand     ZAR

The key argument to sorted ensures that the dictionary's items are sorted by value.

EDIT: as requested, make the field length match the dictionary value length (plus some padding).

Upvotes: 7

Related Questions