Reputation: 649
I need to generate an export (csv) of a series of simple objects like this:
class trx:
def __init__(self,
file_name='',
bank='',
trans_type='',
account=''):
self.filename = file_name
self.bank = bank
self.trans_type = trans_type
self.account = account
What is the simplest way to list the attribute/value pairs in order by attribute? __dict__
changes order every time.
Upvotes: 0
Views: 260
Reputation: 1121814
You could use vars()
on self
, then sort the items:
sorted(vars(self).items())
This then gives you a sorted list of (attributename, value)
pairs.
However, if your class is little more than a container for 4 related datapoints, then consider using a namedtuple
class:
from collections import namedtuple
TRX = namedtuple('TRX', ('file_name', 'bank', 'trans_type', 'account'))
This lists the attributes in named order, always:
>>> from collections import namedtuple
>>> TRX = namedtuple('TRX', ('file_name', 'bank', 'trans_type', 'account'))
>>> TRX('foo.txt', 'Bar PLC', 'withdrawal', '1234xyz')
TRX(file_name='foo.txt', bank='Bar PLC', trans_type='withdrawal', account='1234xyz')
Because the instances are sequences (a subclass of tuple
in fact) you can pass these directly to a csv.writer().writerow()
call; at the same time you can use instance.bank
or instance.file_name
to access the fields.
Another alternative is to use dictionaries, and use csv.DictWriter()
to handle the order (the fieldnames
argument determines the order).
Upvotes: 3