Format: text/x-python
⬇ Download File (493 B)
   1  import csv
   2  from collections import OrderedDict
   3  
   4  
   5  class Pipe:
   6      value = ""
   7  
   8      def write(self, text):
   9          self.value = self.value + text
  10  
  11  
  12  def convert_list_of_dict_to_csv_string(list_of_dicts):
  13      pipe = Pipe()
  14      temp_dict = [OrderedDict(sorted(x.items())) for x in list_of_dicts]
  15      writer = csv.DictWriter(pipe, temp_dict[0].keys())
  16      for entry in temp_dict:
  17          writer.writerow(entry)
  18  
  19      result_str = ",".join(temp_dict[0].keys()) + "\n" + pipe.value
  20      return result_str