Using csv DictWriter - add a extra field

Peter Otten __peter__ at web.de
Tue Mar 31 04:22:46 EDT 2015


Victor Hooi wrote:

> 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?

The latter. The obvious solution is to add the extra field to the dict:

values['connection_id'] = connection
writer.writerow(values)

Or you use a collections.ChainMap (Python 3 only I think, but 
<http://code.activestate.com/recipes/305268/> should work as well here)

writer.writerow(
    collections.ChainMap(values, {"connection_id": connection}))





More information about the Python-list mailing list