python中row_values,将Python字典写入CSV,其中keys = columns,values = rows

I have a list of dictionaries that I want to be able to open in Excel, formatted correctly. This is what I have so far, using csv:

list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]

out_path= "/docs/outfile.txt"

out_file = open(ipath, 'wb')

writer = csv.writer(ofile, dialect = 'excel')

for items in list_of_dicts:

for k,v in items.items():

writer.writerow([k,v])

Obviously, when I open the output in Excel, it's formatted like this:

key value

key value

What I want is this:

key key key

value value value

I can't figure out how to do this, so help would be appreciated. Also, I want the column names to be the dictionary keys, in stead of the default 'A, B, C' etc. Sorry if this is stupid.

Thanks

解决方案

The csv module has a DictWriter class for this, which is covered quite nicely in another SO answer. The critical point is that you need to know all your column headings when you instantiate the DictWriter. You could construct the list of field names from your list_of_dicts, if so your code becomes

list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]

out_path= "/docs/outfile.txt"

out_file = open(out_path, 'wb')

fieldnames = sorted(list(set(k for d in list_of_dicts for k in d)))

writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')

writer.writeheader() # Assumes Python >= 2.7

for row in list_of_dicts:

writer.writerow(row)

out_file.close()

The way I've constructed fieldnames scans the entire list_of_dicts, so it will slow down as the size increases. You should instead construct fieldnames directly from the source of your data e.g. if the source of your data is also a csv file you can use a DictReader and use fieldnames = reader.fieldnames.

You can also replace the for loop with a single call to writer.writerows(list_of_dicts) and use a with block to handle file closure, in which case your code would become

list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]

out_path= "/docs/outfile.txt"

fieldnames = sorted(list(set(k for d in list_of_dicts for k in d)))

with open(out_path, 'wb') as out_file:

writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')

writer.writeheader()

writer.writerows(list_of_dicts)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
创建表格用于显示第一个工作表 columns1 = next(self.record_sheet.iter_rows(min_row=1, max_row=1, values_only=True)) treeview1 = ttk.Treeview(self.container1, columns=columns1, show="headings") treeview1.grid(row=1, column=3, rowspan=1, padx=5, pady=5, sticky="nsew") # 设置表格列的标题和宽度 for col in columns1: treeview1.heading(col, text=col) treeview1.column(col, width=100, anchor="center") # 显示第一个工作表的内容 for row in self.record_sheet.iter_rows(min_row=2, values_only=True): row_values = [cell if cell is not None else "" for cell in row] if all(not bool(cell) for cell in row_values): continue treeview1.insert("", tk.END, values=row_values) # 创建表格用于显示第二个工作表 columns2 = next(self.data_sheet.iter_rows(min_row=1, max_row=1, values_only=True)) treeview2 = ttk.Treeview(self.container1, columns=columns2, show="headings") treeview2.grid(row=3, column=3, padx=5, pady=5, sticky="nsew") # 设置表格列的标题和宽度 for col in columns2: treeview2.heading(col, text=col) treeview2.column(col, width=100, anchor="center") # 显示第二个工作表的内容 for row in self.data_sheet.iter_rows(min_row=2, values_only=True): row_values = [cell if cell is not None else "" for cell in row] if all(not bool(cell) for cell in row_values): continue treeview2.insert("", tk.END, values=row_values) # 设置文本框大小一致 self.material_name1.config(width=20) self.material_qty.config(width=20)將顯示在文本框數據用邊框綫框起來的修改後的完整代碼
最新发布
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值