6

I have a dictionary:

dic={'Tim':3, 'Kate':2}

I would like to output it as:

Name Age
Tim 3
Kate 2

Is it a good way to first convert them into a list of dictionaries,

lst = [{'Name':'Tim', 'Age':3}, {'Name':'Kate', 'Age':2}]

and then write them into a table, by the method in https://stackoverflow.com/a/10373268/156458?

Or is there a way better in some sense?

Community
  • 1
  • 1
Tim
  • 88,294
  • 128
  • 338
  • 543
  • Where are the attribute names stored? – Vedaad Shakib Mar 25 '15 at 19:42
  • possible duplicate of [Python - Printing a dictionary as a horizontal table with headers](http://stackoverflow.com/questions/17330139/python-printing-a-dictionary-as-a-horizontal-table-with-headers) – alexwlchan Mar 25 '15 at 19:43
  • @Ved: in the table, as the first row – Tim Mar 25 '15 at 19:43
  • no need to convert it to a list, print the header row, then iterate through key-value pairs and print the key, followed by the value – Julien Spronck Mar 25 '15 at 19:44
  • Tim, it is better if you add the version you are using. As in [tag:python-2.7] or [tag:python-3.x] – Bhargav Rao Mar 25 '15 at 19:55
  • You can test multiple methods by using the `timeit` module. Here, I have run some tests for you: http://repl.it/f2W/1 To run more intensive tests, I recommend using your terminal because repl.it is slow. Using `dic.items()` seems to be the most consistently fast way. – Shashank Mar 25 '15 at 20:29

6 Answers6

11

Well, you don't have to convert it in a dictionary, you can directly:

print('Name Age')
for name, age in dic.items():
    print('{} {}'.format(name, age))
Francis Colas
  • 2,991
  • 2
  • 24
  • 31
11

You could use pandas.

In [15]: import pandas as pd

In [16]: df = pd.DataFrame({'Tim':3, 'Kate':2}.items(), columns=["name", "age"]) 

In [17]: df
Out[17]: 
   name  age
0   Tim    3
1  Kate    2
Akavall
  • 76,296
  • 45
  • 192
  • 242
4

You can do it directly as in

>>> print("Name\tAge")
Name  Age
>>> for i in dic:
...     print("{}\t{}".format(i,dic[i]))
... 
Tim 3
Kate    2
>>> 

It displays even better if executed as a script

Name    Age
Tim     3
Kate    2

And for the other representation

lst = [{'Name':'Tim', 'Age':3}, {'Name':'Kate', 'Age':2}]
print("Name\tAge")
for i in lst:
    print("{}\t{}".format(i['Name'],i['Age']))

And for your final question - Is it a good way to first convert them into a list of dictionaries Answer is No, A dictionary is hashed and provides faster access than lists

Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
4

You can do it this way,

format = "{:<10}{:<10}"    
    print format.format("Name","Age")
    for name,age in dic.iteritems():
       print format.format(name,age)

I have written a simple library to pretty print dictionary as a table https://github.com/varadchoudhari/Neat-Dictionary which uses a similar implementation

vardos
  • 334
  • 3
  • 13
1

Iterate dictionary and print every item.

Demo:

>>> dic = {'Tim':3, 'Kate':2}
>>> print "Name\tAge"
Name    Age
>>> for i in dic.items():
...    print "%s\t%s"%(i[0], i[1])
... 
Tim 3
Kate    2
>>> 

By CSV module

>>> import csv
>>> dic = {'Tim':3, 'Kate':2}
>>> with open("output.csv", 'wb') as fp:
...     root = csv.writer(fp, delimiter='\t')
...     root.writerow(["Name", "Age"])
...     for i,j in dic.items():
...         root.writerow([i, j])
... 
>>> 

Output: output.csv file content

Name    Age
Tim     3
Kate    2

We can use root.writerows(dic.items()) also

Vivek Sable
  • 9,246
  • 3
  • 34
  • 50
0

If you go for higher numbers, then having number in the first column is usually a safer bet as you never know how long a name can be.

Given python3:

dic={'Foo':1234, 'Bar':5, 'Baz':123467}

This:

print("Count".rjust(9), "Name")
rint("\n".join(f'{v:9,} {k}' for k,v in dic.items()))

Prints

    Count Name
    1,234 Foo
        5 Bar
  123,467 Baz
hansaplast
  • 10,004
  • 2
  • 50
  • 64