Using DictWriter to write a subset of a dictionary's keys

前端 未结 2 933
别那么骄傲
别那么骄傲 2020-12-29 09:48

I wrote a function that serializes a list of dictionaries as a CSV file using the csv module, with code like this:

data = csv.DictWriter(out_f,          


        
相关标签:
2条回答
  • 2020-12-29 10:26

    Changes to your code:

    Forget Dictwriter, use ordinary writer.

    Then loop over your list of dicts:

    for d in dictrows:
        ordinary_writer.writerow([d[fieldname] for fieldname in fieldnames])
    

    Use d.get(fieldname, "") instead of d[fieldname] if you don't want an exception if there is no entry in d for a fieldname.

    Note to anonymous downvoters: This is doing what Alex's solution is doing under the hood (see Lib/csv.py) and doing it a bit better ... csv.py calls a function to get each row in a list, and the guts of that function is

    return [rowdict.get(key, self.restval) for key in self.fieldnames]
    
    0 讨论(0)
  • 2020-12-29 10:41

    Simplest and most direct approach is to pass extrasaction='ignore' when you initialize your DictWriter instance, as documented here:

    If the dictionary passed to the writerow() method contains a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to 'raise' a ValueError is raised. If it is set to 'ignore', extra values in the dictionary are ignored.

    It also works on writerows, which, internally, just calls writerow repeatedly.

    0 讨论(0)
提交回复
热议问题