Print a dictionary into a table
Question:
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?
Answers:
You can do it directly as in
>>> print("NametAge")
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("NametAge")
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
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))
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
Iterate dictionary and print every item.
Demo:
>>> dic = {'Tim':3, 'Kate':2}
>>> print "NametAge"
Name Age
>>> for i in dic.items():
... print "%st%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
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
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
To improve upon Francis Colas’s answer, you can make it simpler by using f strings:
print('Name Age')
for name, age in dic.items():
print(f'{name} {age}')
for each in zip(*([i] + (j) for i, j in c.items())):
print(*each)
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?
You can do it directly as in
>>> print("NametAge")
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("NametAge")
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
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))
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
Iterate dictionary and print every item.
Demo:
>>> dic = {'Tim':3, 'Kate':2}
>>> print "NametAge"
Name Age
>>> for i in dic.items():
... print "%st%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
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
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
To improve upon Francis Colas’s answer, you can make it simpler by using f strings:
print('Name Age')
for name, age in dic.items():
print(f'{name} {age}')
for each in zip(*([i] + (j) for i, j in c.items())):
print(*each)