Using csv DictWriter - add a extra field

Victor Hooi victorhooi at gmail.com
Tue Mar 31 00:47:45 EDT 2015


Hi,

I have a dict named "connections", with items like the following:

In [18]: connections
Out[18]:
{'3424234': {'end_timestamp': datetime.datetime(2015, 3, 25, 5, 31, 30, 406000, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200))),
  'ip_address': '10.168.8.36:52440',
  'open_timestamp': datetime.datetime(2015, 3, 25, 5, 31, 0, 383000, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200))),
  'time_open': datetime.timedelta(0, 30, 23000)}}

In this case, the key is a connection id (e.g. "3424234"), and the value is a another dict, which contains things like 'end_timestamp', 'ip_address" etc.

I'm writing the output of "connections" to a CSV file using DictWriter:

fieldnames = ['connection_id', 'ip_address', 'open_timestamp', 'end_timestamp', 'time_open']
with open('output.csv', 'w') as csvfile:
    writer = DictWriter(csvfile, fieldnames)
    writer.writeheader()
    for connection, values in sorted(connections.items()):
        if 'time_open' in values:
            writer.writerow(values, {'connection_id': connection})
        else:
            pass
            # DO SOME STUFF

The only problem is, I'd also like output the connection_id field as part of each CSV record.

However, connection_id in this case is the key for the parent dict.

Is there a clean way to add a extra field to DictWriter writerows, or it is the contents of the dict and that's it?

Cheers,
Victor



More information about the Python-list mailing list