| | |
Working with files
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved |
•
•
Join Date: Oct 2009
Posts: 18
Reputation:
Solved Threads: 0
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:
I am confused about next steps. Please, help.
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)
def create_dict(f): f = open("something.txt") d = {} for line in f: columns = line.split(",") letters = columns[0] numbers = columns[2]
I am confused about next steps. Please, help.
Last edited by pyprog; Nov 7th, 2009 at 2:28 am.
0
#2 Nov 7th, 2009
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.
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)
def create_dict(): f = open("something.txt") d = {} for line in f: try: columns = line.split(",") letters = columns[0] numbers = columns[2] data = {letters:numbers} d.update(data) except(IndexError): pass print d create_dict()
Last edited by ShadyTyrant; Nov 7th, 2009 at 3:04 am. Reason: May have found solution
0
#3 Nov 7th, 2009
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)
# possible test data data = """\ a,z,1 b,y c,x,1 d,w,1 e,v f,u""" fname = "something.txt" # write test data file ... fout = open(fname, "w") fout.write(data) fout.close() def create_dict(fname): fin = open(fname, "r") d = {} for line in fin: columns = line.split(",") if len(columns) > 2 : letter = columns[0] number = columns[2].rstrip() d[letter] = number return d print( create_dict(fname) ) # {'a': '1', 'c': '1', 'd': '1'}
May 'the Google' be with you!
•
•
Join Date: Nov 2009
Posts: 79
Reputation:
Solved Threads: 25
Resort to regular expressions. Begin with:
Then, if it's OK for the dictionary values to be strings, use:
Otherwise use:
In both cases, the key is
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.
Python Syntax (Toggle Plain Text)
import re s = file('something.txt', 'rt').read()
Python Syntax (Toggle Plain Text)
d = dict( re.findall(r'^(\S),\S,(\d)$', s, re.M) )
Python Syntax (Toggle Plain Text)
d = dict( (key, int(val)) for (key, val) in re.findall(r'^(\S),\S,(\d)$', s, re.M) )
Python Syntax (Toggle Plain Text)
re.findall(r'^(\S),\S,(\d)$', s, re.M)
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.
![]() |
Similar Threads
- Internet suddenly stopped working on Vista (Windows Vista and Windows 7)
- BASH script - sales per each associate (3 files) (Shell Scripting)
- Files in C (C)
- Use Java to remove a block of html from a number of files? (Java)
- Working with Files (Windows tips 'n' tweaks)
Other Threads in the Python Forum
- Previous Thread: Python CGI vs PHP
- Next Thread: Is is possible to format the output of a python program on the command line?
Views: 244 | Replies: 3
| Thread Tools | Search this Thread |
Tag cloud for Python
anti approximation array avogadro beginner builtin cipher clear client code color converter countpasswordentry cturtle curved def dictionary drive dynamic examples excel file float format frange ftp function gui homework import input java lapse library line lines linux list lists loop microcontroller mouse multiple mysqldb mysqlquery newb number numbers output parsing path port prime program programming projects py2exe pygame pymailer pyqt python random recursion recursive redirect script scrolledtext singleton socket sqlite ssh stderr string strings subprocess sum syntax table terminal text textarea thread threading time tkinter tlapse tuple tutorial twoup ubuntu unicode unix urllib urllib2 variable web-scrape wikipedia windows word wxpython






