| | |
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; 21 Days Ago at 2:28 am.
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.
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; 21 Days Ago at 3:04 am. Reason: May have found solution
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 ...
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: 21
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; 18 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 |
address aliased anydbm app bash beginner bits calling casino changecolor cipher clear conversion coordinates corners count cturtle curves definedlines development dictionary digital dynamic events examples excel external feet file float format function gui handling hints homework iframe images import input java keycontrol line linux list lists loan loop matching mouse multiple number numbers output parsing path port prime programming projects py py2exe pygame pymailer python random rational raw_input recursion recursive scrolledtext searchingfile shebang signal singleton split string strings tails terminal text threading time tlapse tooltip tuple tutorial type ubuntu unicode url urllib urllib2 valueerror variable web-scrape whileloop word wxpython xlwt






