I have a dictionary:
JavaScript
x
2
1
dic={'Tim':3, 'Kate':2}
2
I would like to output it as:
JavaScript
1
4
1
Name Age
2
Tim 3
3
Kate 2
4
Is it a good way to first convert them into a list of dictionaries,
JavaScript
1
2
1
lst = [{'Name':'Tim', 'Age':3}, {'Name':'Kate', 'Age':2}]
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?
Advertisement
Answer
Rather than convert to a list of dictionaries, directly use the .items
of the dict to get the values to display on each line:
JavaScript
1
4
1
print('Name Age')
2
for name, age in dic.items():
3
print(f'{name} {age}')
4
In versions before 3.6 (lacking f-string support), we can do:
JavaScript
1
4
1
print('Name Age')
2
for name, age in dic.items():
3
print('{} {}'.format(name, age))
4