以相同的方式写入具有多个列表和字典的文件

时间:2019-02-21 02:31:29

标签: python list dictionary

我成功编写了使用脚本中提供的三个列表的脚本。

作为输出(打开文件),我使用基于这些列表创建的字典。但是,我想以一种可以使用任何数量的列表的方式编写脚本,因此可以以相同的方式在打开的文件中编写任意数量的词典。

dict1 = {'A': 'val1' ,'B': 'val1' ,'C': 'val2' , 'X': 'val2' , 'NAME': 'val5' ,'HA': 'val5' , 'gcay': 'val7' , 'nkd': 'val8'}   #contain all my data
dict2 = {'Consensus1':'val1', 'Consensus2':'val2', 'Consensus3':'val5','Consensus4':'val7','Consensus5':'val8'}  #contain new Keys with only single Val based on dict1 (repetitive Val# are collapse

List1 = ['A','B']  #these can be random names and not the alphabet
List2 = ['C', 'X', 'NAME']
List3 = ['HA', 'gcay', 'nkd']


List1_col = []
for i in List1:
    List1_col.append(dic1[i])  #I have a dictionary that contains all the IDs
freq_List1_col = {key : List1_col.count(i) for i in List1_col for key,value in dict2.items() if value == i} #Here I switch the names for the key,value in another dictionary


List2_col = []
for i in List2:
    List2_col.append(dic1[i]) 
freq_List2_col = {key : List2_col.count(i) for i in List2_col for key,value in dict2.items() if value == i} 

List3_col = []
for i in List3:
    List3_col.append(dic1[i]) 
freq_List3_col = {key : List3_col.count(i) for i in List3_col for key,value in dict2.items() if value == i} 

with open('myfile.txt', 'w') as f:
    header = 'This header appears every time I open a dictionary{\n'

    f.write(header)
    for key,value in freq_List1_col.items():
        out1 = key + 'has ' + value
        f.write(out1)
    f.write('}\n')

    f.write(header)
    for key,value in freq_List2_col.items():
        out2 = key + 'has ' + value
        f.write(out2)
    f.write('}\n')

    f.write(header)
    for key,value in freq_List3_col.items():
        out3 = key + 'has ' + value
        f.write(out3)
    f.write('}\n')

我基本上在每个列表中打开dict2中Key的频率。输出将如下所示:

This header appears every time I open a dictionary{
Consensus1 has 2
}

This header appears every time I open a dictionary{
Consensus2 has 2
Consensus3 has 1
}

This header appears every time I open a dictionary{
Consensus3 has 1
Consensus4 has 1
Consensus5 has 1
}

我在想也许我应该从“列表列表”开始?然后,我可以编写任意数量的列表,因为脚本可能会读取列表中的任何项目 预先感谢!

0 个答案:

没有答案