4

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
  • 1
  • 141
  • 372
  • 590
  • 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

7 Answers7

11

Rather than convert to a list of dictionaries, directly use the .items of the dict to get the values to display on each line:

print('Name Age')
for name, age in dic.items():
    print(f'{name} {age}')

In versions before 3.6 (lacking f-string support), we can do:

print('Name Age')
for name, age in dic.items():
    print('{} {}'.format(name, age))
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Francis Colas
  • 3,459
  • 2
  • 26
  • 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
  • 82,592
  • 51
  • 207
  • 251
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
  • 50,140
  • 28
  • 121
  • 140
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,938
  • 3
  • 40
  • 56
  • how to write, not to a file, but to the console or say the stdout? in other words, how to print in this manner? – user8395964 Apr 19 '23 at 08:42
1

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
  • 11,007
  • 2
  • 61
  • 75
0
for each in zip(*([i] + (j) for i, j in c.items())):
    print(*each) 
NameVergessen
  • 598
  • 8
  • 26
  • for each in zip(*([i]+(j) for i,j in dict.items())): print(*each) – Yash Goyal Nov 24 '22 at 05:10
  • Hey @yash-goyal, consider making your snippet a markdown code block. Doing so would improve legibility for other viewers and your answer looks cooler ;) Hope you enjoy your journey on the platform! – colin Nov 26 '22 at 14:26