2017-10-23 23 views
0

私は、各キー(私の場合は 'CUI')の値の配列に関連付けられているforループを使用してPythonで辞書を作成したいが、私が得る出力は辞書ですキーは私のリストの値のうちの1つだけを返します。私のコードを次に示します。辞書for forループのpython

import numpy as np 
data2 = open('pathways.dat', 'r', errors = 'ignore') 
pathways = data2.readlines() 

special_line_indexes = [] 
PWY_ID = [] 
line_cont = [] 
L_PRMR = [] #Left primary 
dict_comp = dict() 

#i is the line number (first element of enumerate), while line is the line content (2nd elem of enumerate) 
for CUI in just_compound_id: 
    for i,line in enumerate(pathways): 
     if '//' in line: 
      #fint the indexes of the lines containing // 
      special_line_indexes = i+1 
     elif 'REACTION-LAYOUT -' in line: 
      if CUI in line: 
       PWY_ID.append(special_line_indexes) 
       dict_comp[CUI] = special_line_indexes 
print(PWY_ID) 
+1

'dict_compの[のCUI] = special_line_indexes'持つたびに、内側の前に空の配列を取得し

あなたはPWY_ID'に値を追加しているので、 'dict_compの[のCUI] = PWY_ID'する必要があります'。また、構造体ごとにforループのどこかでこのリストをクリアする必要があります。 – ZdaR

答えて

2

あなたは、内側の外に辞書をとり、PWY_IDテーブルをasignする必要があります。

import numpy as np 
data2 = open('pathways.dat', 'r', errors = 'ignore') 
pathways = data2.readlines() 

special_line_indexes = [] 
line_cont = [] 
L_PRMR = [] #Left primary 
dict_comp = dict() 

#i is the line number (first element of enumerate), while line is the line content (2nd elem of enumerate) 
for CUI in just_compound_id: 
    PWY_ID = [] 
    for i,line in enumerate(pathways): 
     if '//' in line: 
      #fint the indexes of the lines containing // 
      special_line_indexes = i+1 
     elif 'REACTION-LAYOUT -' in line: 
      if CUI in line: 
       PWY_ID.append(special_line_indexes) 
    dict_comp[CUI] = PWY_ID 
print(PWY_ID) 
print (dict_comp) 

EDIT あなたは以上の値を足すされているので、それはだ理由辞書インデックス(CUI)は毎回値の配列ではなく値(special_line_indexes)を使用します。あなたが必要とするのは、内側のテーブルを(PWY_ID(append)で)作成し、各ループに1つの要素を追加し、それを作成したら、forループを終了したら、その配列を辞書に割り当てる必要があります(dict_comp [CUI] = PWY_ID)。あなたはPWY_ID = []

+0

なぜこれら2つのステップが必要なのか説明できますか? – StudentOIST

+0

私は私の答えにコメントを追加しました。理由を説明してくれることを願って – nacho

関連する問題