user4164101
user4164101

Reputation:

Reading a file to a dictionary

I have this function which reads a file with 6 rows and 4 columns in each row, a row can look like this:

SCV-A.ST,12,118.20,"10/1/2012"

What I am trying to do is saving the read file to a dictionary where the first column ("SCV-A.ST" in this case) is the key and a string. Rest of the row is a list where the second column an integer, third is a float, and the last is a string.

My function which reads the file looks like this

def read_file(filename):
        f = open(filename, 'r')
        s = f.read()
        return s

And I have no clue where to go from here, I tried splitting it and joining again but no cigar, appreciate any input at this point.

Thanks!

Upvotes: 0

Views: 97

Answers (2)

Sujal Sheth
Sujal Sheth

Reputation: 392

I think below code would work for your requirement

try:
    in_file = raw_input("Enter a file name:")
    myfile = open(in_file)
except :
    print "Couldn't open the file"
    exit()

d = dict()
for line in myfile :
    line = line.strip()
    elements = line.split(",")
    d[str(elements[0])] = [(int(elements[1]),float(elements[2]), str(elements[3]))]

for key in d :
        print key, d[key]

Input file: myfile.txt

SCV-A.ST,12,118.20,"10/1/2012"
SCV-B.ST,13,119.20,"10/1/2013"
SCV-C.ST,14,120.20,"10/1/2014"
SCV-D.ST,15,121.20,"10/1/2015"
SCV-E.ST,16,122.20,"10/1/2016"

Output of program:

Enter a file name:myfile.txt

SCV-A.ST [(12, 118.2, '"10/1/2012"')]
SCV-C.ST [(14, 120.2, '"10/1/2014"')]
SCV-B.ST [(13, 119.2, '"10/1/2013"')]
SCV-E.ST [(16, 122.2, '"10/1/2016"')]
SCV-D.ST [(15, 121.2, '"10/1/2015"')]

You can probably write short routine to search in directory based upon user input too.

Upvotes: 0

Jeff M.
Jeff M.

Reputation: 1087

I would use the csv package:

import csv

f = open('/path/to/file','rb')

reader = csv.reader(f)

newDict = {}
for row in reader:
    newDict[str(row[0])]=[row[1],row[2],row[3]]

print(newDict)

This will yield the following with the row you provided:

{'SCV-A.ST': ['12', '118.20', '10/1/2012']}

It may also be valuable to convert convert row[1] to an integer using int(), row[2] to a float using float(), and row[3] to a date object using the datetime package

Upvotes: 1

Related Questions