News for hackers. Stuff that matters.
Re:Advanced Python Mastery – A Course by David Beazley by nicwolff on Wednesday July 19, 2023 @11:13AM (#36787803)
Whenever you see this pattern, think of using a generator instead:

    def read_portfolio(filename):
        with open(filename) as f:
            rows = csv.reader(f)
            headers = next(rows)
            for row in rows:
                yield {
                    'name' : row[0],
                    'shares' : int(row[1]),
                    'price' : float(row[2]),
                }
Now you can call read_portfolio() to get an iterable that lazily reads the file and yields dicts:

    portfolio = read_portfolio()
    for record in portfolio:
        print '{shares} shares of {name} at ${price}'.format_map(record)
Re:Advanced Python Mastery – A Course by David Beazley by drexlspivey on Wednesday July 19, 2023 @11:21AM (#36787921)
or use the built-in csv.DictReader :)