Printing a dictionary into a table

I have a dictionary:

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

I would like to output it as:

Name Age
Tim 3
Kate 2

This is a good way to convert them to a list of dictionaries first,

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

and then write them to the table using the method https://stackoverflow.com/a/146908/ ?

Or is there some way in a way?

+2
source share
5 answers

Well, you do not need to convert it to a dictionary, you can directly:

print('Name Age')
for name, age in dic.items():
    print('{} {}'.format(name, age))
+3
source

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 another view

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

- . . ,

+2

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
+2

.

:

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

CSV

>>> 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.csv

Name    Age
Tim     3
Kate    2

root.writerows(dic.items())

+1

,

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

https://github.com/varadchoudhari/Neat-Dictionary

+1

Source: https://habr.com/ru/post/1670513/


All Articles