Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJoshua Emanuel
3,270 PointsRegex Extra Credit - How do I sort address_book?
Can't work out how to reference the object instances sitting inside the address_book instance and the associated attributes that are held there. Feels as though it's possible I just can't work out how to access them?
import re
with open('C:/Users/Joshua Emanuel/PycharmProjects/Treehouse/Better Python/names', encoding='utf-8') as open_file:
data = open_file.read()
line = re.compile(r'''
^(?P<name>(?P<last>[-\w ]*),\s(?P<first>[-\w ]+))\t
(?P<email>[-\w\d.+]+ @[-\w\d.]+)\t
(?P<phone>\(?\d{3}\)?-?\s?\d{3}-\d{4})?\t
(?P<job>[\w\s]+,\s[\w\s.]+)\t?
(?P<twitter>@[\w\d]+)?$
''', re.X | re.M)
class Person():
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
def __repr__(self):
return repr(self.first + " " + self.last)
def __sort__(self):
return self.last
@classmethod
def construct(cls, list, line, data):
for match in line.finditer(data):
list.append(cls(**match.groupdict()))
class AddressBook(list):
def __init__(self):
super().__init__()
def show_book(self):
for person in self:
print(f'{person.first} {person.last}')
def __sort__(self):
list.sort(self)
address_book = AddressBook()
Person.construct(address_book, line, data)
1 Answer
Steven Parker
231,269 PointsThe "sort" method takes an optional "key" function which can be used to retrieve an attribute to sort on:
self.sort(key=lambda person: person.last) # sort by last name