By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,607 Members | 1,156 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,607 IT Pros & Developers. It's quick & easy.

Read from file into dictionary

P: 5
if this was my input file:
Expand|Select|Wrap|Line Numbers
  1. AATGC
  2. AGGC
  3. 0.0
  4. 0.0
  5. 4
  6. ATGC
  7. 4
  8. ATGC
  9. 1 1 A A 1
  10. 1 2 A T 0
  11. 1 3 A G 0
  12. 1 4 A C 0
  13. 2 1 T A 0
  14. 2 2 T T 1
  15. 2 3 T G 0
  16. 2 4 T C 0
  17. 3 1 G A 0
  18. 3 2 G T 0
  19. 3 3 G G 1
  20. 3 4 G C 0
  21. 4 1 C A 0
  22. 4 2 C T 0
  23. 4 3 C G 0
  24. 4 4 C C 1
  25.  
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!
May 16 '12 #1
Share this Question
Share on Google+
1 Reply

P: 5
Expand|Select|Wrap|Line Numbers
  1. result = dict()
  2.  
  3. with open('filename.txt', 'r') as source_file:
  4.     for line in source_file.readlines():
  5.         parts = line.split()
  6.         if len(parts) < 5: continue
  7.         key = '{0}{1}'.format(parts[2], parts[3])
  8.         result[key] = parts[4]
  9.  
  10. print result
May 17 '12 #2

Post your reply

Sign in to post your reply or Sign up for a free account.