【发布时间】:2016-11-10 03:28:29
【问题描述】:
我正在尝试创建一个包含多个字典的字典。我是从 .txt 文件创建的:
chrY 6 8 +
chrY 3 5 +
chrX 10 11 +
chrX 13 15 -
我想要的输出是:
{'chrY': {'+' : {'start': [3 , 6], 'end': [5, 8]}}, 'chrX': {'+' : {'start': [10], 'end': [11]} , '-': {'start' : [13], 'end' : [15]}}}
到目前为止,我的代码包括:
import sys
first_dict = {}
intron_dict = {}
def main():
with open(sys.argv[1], 'r') as intron:
for line in intron.readlines():
line = line.split()
chromosome = line[0]
start = line[1]
end = line[2]
strand = line[3]
first_dict = {chromosome : (strand, start, end)}
for k, v in first_dict.iteritems():
intron_dict.setdefault(k, []).append(v)
print (intron_dict)
if __name__=='__main__':
main()
此代码允许我对 chrY 和 chrX 键进行排序,而不会覆盖值。我在合并“+”和“-”键并将数据转换为我想要的格式时遇到问题。到目前为止,我的输出看起来像:
{'chrY': [('+', '6', '8'), ('+', '3', '5')], 'chrX': [('+', '10', '11'), ('-', '13', '15')]}
【问题讨论】:
标签: python dictionary nested