Working with files

Thread Solved

Join Date: Oct 2009
Posts: 18
Reputation: pyprog is an unknown quantity at this point 
Solved Threads: 0
pyprog pyprog is offline Offline
Newbie Poster

Working with files

 
0
  #1
21 Days Ago
I have a file like this:
a,z,1
b,y
c,x,1
d,w,1
e,v
f,u
What I need to do is to create a dictionary that has the characters in the first column as keys and characters in the third column as values. The rest should be ignored, i.e. {a:1, c:1, d:1}. This is what I have so far:
  1. def create_dict(f):
  2. f = open("something.txt")
  3. d = {}
  4. for line in f:
  5. columns = line.split(",")
  6. letters = columns[0]
  7. numbers = columns[2]

I am confused about next steps. Please, help.
Last edited by pyprog; 21 Days Ago at 2:28 am.
Reply With Quote Quick reply to this message  
Join Date: Nov 2009
Posts: 31
Reputation: ShadyTyrant is an unknown quantity at this point 
Solved Threads: 5
ShadyTyrant's Avatar
ShadyTyrant ShadyTyrant is offline Offline
Light Poster
 
0
  #2
21 Days Ago
The only problem is the txt file must have 3 rows or the index becomes out of range.
Edit: You can use a Try Except block to only update the dict if there is a value in the 3ed row.

  1. def create_dict():
  2. f = open("something.txt")
  3. d = {}
  4. for line in f:
  5. try:
  6. columns = line.split(",")
  7. letters = columns[0]
  8. numbers = columns[2]
  9. data = {letters:numbers}
  10. d.update(data)
  11. except(IndexError):
  12. pass
  13.  
  14. print d
  15.  
  16. create_dict()
Last edited by ShadyTyrant; 21 Days Ago at 3:04 am. Reason: May have found solution
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,003
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 928
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite
 
0
  #3
20 Days Ago
I usually whip up a little test program. Here you use the length of your columns list to avoid problems ...
  1. # possible test data
  2. data = """\
  3. a,z,1
  4. b,y
  5. c,x,1
  6. d,w,1
  7. e,v
  8. f,u"""
  9.  
  10. fname = "something.txt"
  11.  
  12. # write test data file ...
  13. fout = open(fname, "w")
  14. fout.write(data)
  15. fout.close()
  16.  
  17.  
  18. def create_dict(fname):
  19. fin = open(fname, "r")
  20. d = {}
  21. for line in fin:
  22. columns = line.split(",")
  23. if len(columns) > 2 :
  24. letter = columns[0]
  25. number = columns[2].rstrip()
  26. d[letter] = number
  27. return d
  28.  
  29. print( create_dict(fname) ) # {'a': '1', 'c': '1', 'd': '1'}
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Nov 2009
Posts: 79
Reputation: pythopian is an unknown quantity at this point 
Solved Threads: 21
pythopian pythopian is offline Offline
Junior Poster in Training

Don't get too noisy, try this much shorter hack...

 
0
  #4
18 Days Ago
Resort to regular expressions. Begin with:
  1. import re
  2. s = file('something.txt', 'rt').read()
Then, if it's OK for the dictionary values to be strings, use:
  1. d = dict( re.findall(r'^(\S),\S,(\d)$', s, re.M) )
Otherwise use:
  1. d = dict( (key, int(val)) for (key, val) in re.findall(r'^(\S),\S,(\d)$', s, re.M) )
In both cases, the key is
  1. re.findall(r'^(\S),\S,(\d)$', s, re.M)
It will extract only the lines that match the expected pattern (non-blank,non-blank,digit), and return a list of tuples containing the 1st and 3rd item. All that's left to do then is to convert these tuples into a dictionary of the desired format (string => string or string => int).

Depending on what your expected pattern is, you may substitute '\W' or '[A-Za-z]' for '\S'. Consult the re module docs for more information.
Last edited by pythopian; 18 Days Ago at 12:17 pm.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC