简体   繁体   English

Python将字典输出到Excel文件

[英]Python outputting a dictionary into excel file

I have a dictionary in a txt format - this is part of the file (it contains 6000 keys:values: 我有一个txt格式的字典-这是文件的一部分(它包含6000个键:值:

{'YAL008W': 25, 'YBR255W': 50, 'YGR164W': 37, 'YGR131W': 40, 'YNL003C': 11, 'YBR135W': 2, 'YBR160W': 6, 'YJL082W': 79, 'YJL142C': 4, 'YPL191C': 38, 'YGL215W': 31, 'YKL074C': 33, 'YJL077C': 67, 'YKL096W-A': 22, 'YIL124W': 60, 'YLR364C-A': 2, 'YPL039W': 58, 'YNL170W': 16, 'YGL141W': 62, 'YJL179W': 15, 'YDR316W-A': 13, 'YDR316W-B': 139, 'YKL083W': 25, 'YOR009W': 25, 'YKL029C': 395, 'YPL166W': 31, 'YKL052C': 20, 'YOL034W': 29, 'YBL008W': 42}

I would like to output this dictionary into Excel. 我想将此字典输出到Excel。 Excel takes up tab-delimited file format. Excel占用制表符分隔的文件格式。 Another way I can go about it is to create two lists and get rid of single quote around 'key'. 我可以采用的另一种方法是创建两个列表,并删除“键”周围的单引号。 Any help is much appreciated. 任何帮助深表感谢。 Thank you! 谢谢!

Use the csv module to produce Excel-acceptable output. 使用csv模块产生Excel可接受的输出。 The default dialect is Excel compatible using commas, but you can also switch to a tab-delimited dialect. 默认的方言使用逗号兼容Excel,但是您也可以切换到制表符分隔的方言。

Outputing the dictionary as key-value pairs: 将字典作为键值对输出:

import csv

with open(outputfilename, 'wb') as outfile:
    writer = csv.writer(outfile)
    # to get tabs use csv.writer(outfile, dialect='excel-tab')
    writer.writerows(your_dictionary.iteritems())

You could use the really nice library: xlsxwriter - http://xlsxwriter.readthedocs.org/index.html and just create the Excel very neatly. 您可以使用非常漂亮的库:xlsxwriter- http ://xlsxwriter.readthedocs.org/index.html,并且非常整洁地创建Excel。

-- -

You could also use pandas and its ExcelWriter function. 您还可以使用熊猫及其ExcelWriter函数。 The basic idea is: 基本思想是:

from pandas import DataFrame, ExcelWriter

myDF = DataFrame(myDictionary)
writer = ExcelWriter(someFileName)
myDF.to_excel(writer)
writer.save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM