Read from file into dictionary

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • growthndevlpmnt
    New Member
    • May 2012
    • 5

    Read from file into dictionary

    if this was my input file:
    Code:
    AATGC
    AGGC
    0.0
    0.0
    4
    ATGC
    4
    ATGC
    1 1 A A 1
    1 2 A T 0
    1 3 A G 0
    1 4 A C 0
    2 1 T A 0
    2 2 T T 1
    2 3 T G 0
    2 4 T C 0
    3 1 G A 0
    3 2 G T 0
    3 3 G G 1
    3 4 G C 0
    4 1 C A 0
    4 2 C T 0
    4 3 C G 0
    4 4 C C 1
    How could I generate a dictionary using the last 16 lines? I would like to combine the two letters and use them as a key, and then us the last int as the value stored at the key.

    This is supposed to be a scoring matrix. If there is a better way to do this, by all means please help me be more efficient.

    there will be files that have ints longer than one digit. So i tried to dump the contents into a list and iterate/take slices, but it did not work.

    Please help!
  • andrean
    New Member
    • May 2012
    • 5

    #2
    Code:
    result = dict()
    
    with open('filename.txt', 'r') as source_file:
        for line in source_file.readlines():
            parts = line.split()
            if len(parts) < 5: continue
            key = '{0}{1}'.format(parts[2], parts[3])
            result[key] = parts[4]
    
    print result

    Comment

    Working...