| | |
Working with files
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; 19 Days Ago at 2:28 am.
0
#2 19 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.
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; 19 Days Ago at 3:04 am. Reason: May have found solution
0
#3 19 Days Ago
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: 20
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; 17 Days Ago 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?
| Thread Tools | Search this Thread |
accessdenied advanced apache application argv beginner book change command convert csv cursor def dictionary digital dynamic dynamically edit enter event examples file float format frange function google gui homework i/o import inches input jaunty java keyboard lapse library line lines linux list lists loop microphone mouse movingimageswithpygame newb number numbers numeric obexftp output parameters parsing path phonebook port prime programming projects py2exe pygame pygtk pyopengl python random recursion redirect remote return reverse scrolledtext session simple skinning software sprite statictext string strings syntax terminal text threading time tkinter tlapse trick tuple tutorial ubuntu unicode unit urllib urllib2 variable voip web-scrape wxpython






