所以我有一本这样的字典,这个字典是从一个列表中创建的
list= ['SAP', 'LUF']
fastqs = []
sample_dict = dict((sample,[]) for sample in list)
print(sample_dict)
for k in sample_dict:
for z in fastqs:
if k in z:
sample_dict[k].append(z)
print(sample_dict)
dict_items([('SAP', ['SAP_MM_1.gz', 'SAP_MM_2.gz']), ('LUF',['LUF_1.gz', 'LUF_2.gz'])])
现在我需要把上面的字典分开,因为我想把这些部分看作,
Dic1 = {'SAP': ['SAP_MM_1.gz'],
'LUF': ['LUF_1.gz']}
Dic2 = {'SAP': ['SAP_MM_2.gz'],
'LUF': ['LUF_2.gz']}
从拆分字典中,我需要进一步使用值和键将它们打印到文件中。
例如,首先将字典拆分为,
Dic1={x:sample_dict[x][0] for x in sample_dict}
Dic2={x:sample_dict[x][1] for x in sample_dict}
然后遍历字典中所有keys
的for循环。
for sam in Dic1.keys():
ymlFile = sam + '_job.yml'
ymlFH = open(ymlFile, 'w')
# writing
ymlFH.write("reads1: [\n")
ln1=len(Dic1[sam])
ct1=0
for R1 in sorted(Dic1[sam]):
ct1+=0
if ct1 <= ln1:
ymlFH.write(" {class: File, path: " + R1 + "},\n")
elif ct1 == ln1 :
ymlFH.write(" {class: File, path: "+ R1 + "}\n")
ymlFH.write("]\n")
现在,I期望两个文件被写入到ymlFH
文件中,并在for循环中包含所有定义的步骤。但只写了一个文件。也就是说,只有一个键被写入ymlFH
。
发布于 2019-01-30 18:27:21
我猜你是说sample_dict
是这样的
sample_dict={
'SAP':['SAP_MM_1.gz', 'SAP_MM_2.gz'],
'LUF':['LUF_1.gz', 'LUF_2.gz']
}
你可以做些解释
Dic1={x:sample_dict[x][0] for x in sample_dict}
Dic2={x:sample_dict[x][1] for x in sample_dict}
如果您想像这里的{'SAP': ['SAP_MM_1.gz'],....
一样将值保存在列表中,那么您可以将值一边放在括号中,如下所示
Dic1={x:[sample_dict[x][0]] for x in sample_dict}
编辑
由于sample_dict
中的列表似乎并不总是从排序开始,所以我们可以在理解dict之前快速地对它们进行排序。
for x in sample_dict:
sample_dict[x].sort()
注意:这个简单的方法确实假设列表中的所有文件名都是好的、统一的,并且按照我们的要求排序。如果不是这样的话,那就更棘手了
发布于 2019-01-30 18:47:41
单线:
d = {
'SAP':['SAP_MM_1.gz', 'SAP_MM_2.gz'],
'LUF':['LUF_1.gz', 'LUF_2.gz']
}
l = [{'SAP':[i], 'LUF':[j]} for i, j in zip(d['SAP'], d['LUF'])]
# [{'LUF': ['LUF_1.gz'], 'SAP': ['SAP_MM_1.gz']},
# {'LUF': ['LUF_2.gz'], 'SAP': ['SAP_MM_2.gz']}]
https://stackoverflow.com/questions/54447137
复制相似问题