In: Computer Science
Write a function pretty_print, which takes one parameter that can be any type of namedtuple. It "pretty prints" the contents of the namedtuple, including both the names of its fields and their values. This is subject to a few rules.
A couple of examples follow.
>>> from collections import namedtuple >>> Point = namedtuple('Point', ['x', 'y', 'z']) >>> pt = Point(z = 5, x = 9, y = 13) >>> pretty_print(pt) x: 9 y: 13 z: 5 >>> Person = namedtuple('Person', ['name', 'age', 'favorite']) >>> instructor = Person(name = 'Alex', age = 45, favorite = 'Boo') >>> pretty_print(instructor) name: Alex age: 45 favorite: Boo
Code:
from collections import namedtuple
def pretty_print(pt):
for i in range(len(pt)):#this loop iterates untill the len of
pt
print(pt._fields[i],":",pt[i])#here we print the output in the
format
Point = namedtuple('Point', ['x', 'y', 'z'])
pt = Point(z = 5, x = 9, y = 13)
pretty_print(pt)
Person = namedtuple('Person', ['name', 'age', 'favorite'])
instructor = Person(name = 'Alex', age = 45, favorite =
'Boo')
pretty_print(instructor)
Output: