Search code examples
pythonpython-2.7dictionarytuplesordereddictionary

Python: Cleanest way to write tuples as rows of a DictWriter?


Given:

with open('results.csv', 'wb') as csvfile:
    fieldnames = ['Name', 'Address', '#Reviews']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow(row)

And a list of tuples, each containing a name, address, and #reviews e.g.

[('Name2', 'Main St', 2), ('Name2', 'The Hill', 7), ('Name1', 'The Square', 14)]

I'm trying to write each tuple as a row in the csv using writer.writerow(). I could create a dict for each tuple, thus:

In [95]: for tup in z:
   ....:     row = {"Name": tup[0], "Address": tup[1], "#Reviews": tup[2]}
   ....:     print row

But (i) it's convoluted and more importantly (ii) the order gets lost in the dict creation, and the order will not match that of fieldnames.

I could use an OrderedDict(), but again that seems a little convoluted.

What's a neater/shorter way of achieving this?


Solution

  • If your data isn't formatted as a dict, why are you using DictWriter? Just use a normal csv.writer:

    with open('results.csv', 'wb') as csvfile:
        fieldnames = ['Name', 'Address', '#Reviews']
        writer = csv.writer(csvfile)
        writer.writerow(fieldnames)
        writer.writerows(z) # z is a list of all rows to write
    

    Simpler, faster, and much less code.