Search code examples
pythonlistcsvdictionaryordereddictionary

Saving the exact columns of list in csv in Python


Have the list of lists "d" like that:

[OrderedDict([('id', '1'),
              ('name', 'Jack'),
              ('email', '[email protected]'),
 OrderedDict([('id', '2'),
              ('name', 'Ricky'),
              ('email', '[email protected]')]

I would like to save the output using csv module but without id line (so with columns Name, Email and their values). Performing like this:

path='/..'
fields=['Name','Email']

with open(path, 'w') as f:   
writer = csv.writer(f)
writer.writerow(fields)
for item in new_d:
    writer.writerow([d[1], d[2]])

So it saves me the whole line as a value. How is it possible to get deeper to the level of values of the list and save them properly in csv?


Solution

  • You are almost there:

    from collections import OrderedDict
    import csv
    
    listOfDicts = [OrderedDict([('id', '1'),
                  ('name', 'Jack'),
                  ('email', '[email protected]')]),
                  OrderedDict([('id', '2'),
                  ('name', 'Ricky'),
                  ('email', '[email protected]')])]
    path='someFilename.csv'
    fields=['Name','Email']
    
    with open(path, 'w', newline="", encoding="utf8") as f:   
        writer = csv.writer(f)
        writer.writerow(fields)
        for d in listOfDicts:  # d are your different dictionaries 
            writer.writerow([d['name'], d['email']])
    

    creates the file :

    Name,Email
    Jack,[email protected]
    Ricky,[email protected]
    

    It is important to open(..) the file with newline="" so you do not get additional newlines into it - csv will handle those on its own - you also should specifiy the encoding - just to make sure.

    I fixed some other indentation and minor parenthesis errors on your example data on the way and provided the needed imports to get a working example.

    csv-writer