0

I want to create a dictionary in python using a for loop, where each key ('CUI' in my case)is associated with an array of values, but the output I obtain is a dictionary where each key yeld just one of the values in my list. Following my code:

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
  • 1
    dict_comp[CUI] = special_line_indexes, should be dict_comp[CUI] = PWY_ID, since you have been appending value to PWY_ID. Also you need to clear this list somewhere in the for loops as per your structure. Commented Oct 23, 2017 at 6:06

1 Answer 1

2

You need to take the dictionary out of the inner for and asign the PWY_ID table:

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 The reason it's because you are over writting the value of the dictionary index (CUI) every time with a value (special_line_indexes) instead of an array of values. What you need it's to create the table in the inner for (with PWY_ID(append)), adding one element on each loop, and once you have created it, when you are finished with the for loop, then you need to assign that array to the dictionary (dict_comp[CUI] = PWY_ID).

You get an empty array before the inner for each time with the PWY_ID = []

Sign up to request clarification or add additional context in comments.

2 Comments

Could you explain why those two steps are necessary?
I added a comment in my answer. Hope it explains the reason

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.