944,044 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 387
  • Python RSS
Nov 7th, 2009
0

Working with files

Expand Post »
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:
Python Syntax (Toggle Plain Text)
  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; Nov 7th, 2009 at 2:28 am.
Similar Threads
Reputation Points: 10
Solved Threads: 0
Light Poster
pyprog is offline Offline
31 posts
since Oct 2009
Nov 7th, 2009
0
Re: Working with files
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.

Python Syntax (Toggle Plain Text)
  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; Nov 7th, 2009 at 3:04 am. Reason: May have found solution
Reputation Points: 10
Solved Threads: 19
Junior Poster
ShadyTyrant is offline Offline
120 posts
since Nov 2009
Nov 7th, 2009
0
Re: Working with files
I usually whip up a little test program. Here you use the length of your columns list to avoid problems ...
Python Syntax (Toggle Plain Text)
  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'}
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Nov 9th, 2009
0

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

Resort to regular expressions. Begin with:
Python Syntax (Toggle Plain Text)
  1. import re
  2. s = file('something.txt', 'rt').read()
Then, if it's OK for the dictionary values to be strings, use:
Python Syntax (Toggle Plain Text)
  1. d = dict( re.findall(r'^(\S),\S,(\d)$', s, re.M) )
Otherwise use:
Python Syntax (Toggle Plain Text)
  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
Python Syntax (Toggle Plain Text)
  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; Nov 9th, 2009 at 12:17 pm.
Reputation Points: 20
Solved Threads: 25
Junior Poster in Training
pythopian is offline Offline
81 posts
since Nov 2009

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: Python CGI vs PHP
Next Thread in Python Forum Timeline: Filename as an argument





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC