如何在python中格式化字典的输出

时间:2015-06-11 00:56:38

标签: python dictionary

我想在python中格式化字典的值。这是我用来生成输出的脚本

entries = {}
entries1 = {}

with open('no_dup.txt', 'r') as fh_in:
    for line in fh_in:
        if line.startswith('E'):
            line = line.strip()
            line = line.split()
            entry = line[0]
            if entry in entries:
                entries[entry].append(line)
            else:
                entries[entry] = [line]

with open('no_dup_out.txt', 'w') as fh_out:
    for kee, val in entries.iteritems():
        if len(val) == 1:
            fh_out.write("{} \n".format(val))


with open('no_dup_out.txt', 'r') as fh_in2:
    for line in fh_in2:
        line = line.strip()
        line = line.split()
        entry = line[1]
        if entry in entries1:
            entries1[entry].append(line)
        else:
            entries1[entry] = [line]


with open('no_dup_out_final.txt', 'w') as fh_out2:
    for kee, val in entries1.iteritems():
        if len(val) == 1:
            fh_out2.write("{} \n".format(val))

例如,通过运行上面的脚本,我生成了以下输出

[["[['ENSGMOG00000003747',", "'ENSORLG00000006947']]"]] 
[["[['ENSGMOG00000003752',", "'ENSORLG00000005385']]"]] 
[["[['ENSGMOG00000003760',", "'ENSORLG00000005379']]"]] 
[["[['ENSGMOG00000003748',", "'ENSORLG00000004636']]"]] 
[["[['ENSGMOG00000003761',", "'ENSORLG00000005382']]"]] 

我想格式化它,例如我删除所有括号和逗号(ENSGMOG00000003747 ENSORLG00000006947)并输出其余部分,因为它使用制表符分隔格式。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

如果您的列表列表是full_list,那么您可以使用以下代码提供所需的输出:

desired_list = ['\t'.join([element.split('\'')[1] for element in list_item[0]]) for list_item in full_list]