[Tutor] Playing with generators
Leam Hall
leamhall at gmail.com
Wed Aug 10 07:32:43 EDT 2022
I'm wondering if there's a way to combine "make_person" with the generator in "for fname, peep in". Even if it can be done, should it be done? Or would the code be overly complex?
The goal is to parse a group of data, and create a dict where the value is an object created from the data, and the key is an attribute of the object itself.
class Person():
def __init__(self, data = {}):
self.fname = data.get('fname', 'fred')
self.lname = data.get('lname', 'frank')
data = [
{ 'fname':'Wilbur', 'lname':'Lefron' },
{ 'fname':'Al', 'lname':'Lefron' },
{ 'fname':'Jo', 'lname':'Franco' },
{ 'fname':'Mon', 'lname':'Pascal' },
{ 'fname':'Gray', 'lname':'Webb-Marston'},
]
def make_person(data):
ps = ( Person(d) for d in data)
return ps
peeps = {}
for fname, peep in ( (p.fname, p) for p in make_person(data) ):
peeps[fname] = peep
for person in peeps.values():
print(person.lname)
--
Automation Engineer (reuel.net/resume)
Scribe: The Domici War (domiciwar.net)
General Ne'er-do-well (github.com/LeamHall)
More information about the Tutor
mailing list