2017-08-07 54 views
-1

enter image description here添加对键和值与dict

我想上面的格式输入格式转换成类型的字典列表。

基本上我想要的是将文件的内容转换成一个字典列表。然而,每次运行代码时,我都会得到相同的输出:[{'Similar:similar5,'Score':score5,'Compound':smi}]。这意味着只有一个字典创建,当我的目标是创建5个字符(每行一个)。 有人可以帮我解决这个问题吗?

dt = [] # Creates a list to store dicts 
with open('sample_text.out') as f: # Opens the target text file 
    for line in f: 

     if line.startswith('Compound'): 
      smi = line.split()[1] 
      dt.append({'Compound' : smi}) # Add smi as a value in a dict inside the list 'dt' 

     else: # This part will iterate over the next few lines, split them and add them to the growing list of dicts 

      new_line = line.split() 
      similar = new_line[0] 
      score = new_line[1] 
      print new_line 
      for dicts in dt: 
       dicts['Similar'] = similar 
       dicts['Score'] = score 


print dt 
+0

在什么时候被你认为此代码创建第二个字典? (什么是dt中的字典:dicts ['teste'] = new_line'打算做什么?) – user2357112

+0

这段代码创建一个字典的唯一部分是'{'Compound':smi}',它只针对行从“Compound”开始。 – user2357112

+0

我真正想要的是创建5个字符(每行一个)。但是我没有做到。 –

回答

1

这试图解决一些设计上的缺陷在你的代码和输出你的愿望:

dictionaries = [] # Creates a list to store dicts 

with open('sample_text.out') as input_file: # Opens the target text file 

    compound = None 

    for line in input_file: 

     if line.startswith('Compound'): 
      _, smi = line.split() 
      compound = smi 
     else: 
      similar, score = line.split() 
      dictionaries.append({'Similar': similar, 'Score': score}) 
      dictionaries[-1]['Compound'] = compound 

print(dictionaries) 
+0

谢谢你的IClane!输出很好。但是我不明白line _,smi = line.split()。为什么我不能写smi = line.split()? –

+0

@MarcosSantana,你有'smi = line.split()[1]'这很好,我只是对'_,smi = line.split()'做了一个转换 - 在这两种情况下,分裂,我们只想要第二个。要么工作,我只是倾向于尽可能避免数字。 – cdlane