Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print 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

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?

like image 484
Tim Avatar asked Mar 25 '15 19:03

Tim


People also ask

How do you turn a dictionary into a data frame?

We can convert a dictionary to a pandas dataframe by using the pd. DataFrame. from_dict() class-method.

Can you print a dictionary Python?

Use print() to print a dictionary Call print(value) with a dictionary as value to print the entire dictionary.

How do I print a dictionary object?

Print a dictionary line by line using for loop & dict. items() dict. items() returns an iterable view object of the dictionary that we can use to iterate over the contents of the dictionary, i.e. key-value pairs in the dictionary and print them line by line i.e.


1 Answers

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))
like image 156
Francis Colas Avatar answered Oct 31 '22 08:10

Francis Colas