Newbie
Newbie

Reputation: 163

Python reading file to dictionary

templist=[]
temp=[]
templist2=[]
tempstat1={}
station1={}
station2={}
import os.path 

def main():

    #file name=animallog.txt       
    endofprogram=False 
    try:
        filename=input("Enter name of input file >")
        file=open(filename,"r")
    except IOError:
        print("File does not exist")
        endofprogram=True

    for line in file:
        line=line.strip('\n')

        if (len(line)!=0)and line[0]!='#':          
            (x,y,z)=line.split(':')

            record=(x,z)

            if record[0] not in station1 or record[0] not in station2:

                if record[1]=='s1' and record[0] not in station1:
                    station1[0]=1

                if record[1]=='s2' and record[0] not in station2:
                    station2[0]=1

            elif record[0] in station1 or record[0] in station2:

                if record[1]=='s1':
                    station1[0]=station1[0]+1
                elif record[1]=='s2':
                    station2[0]=station2[0]+1 

    print(station1)
    print(station2)

main()

Hi guys!

I was just working on a program that reads from a file of this format:GIVEN AT THE BOTTOM

But for some reason the output is {0:1} for both station1 and station2 . I was just wondering why this was happening? I tried using the debug function but not able to understand. Appreciate all your effort! Thanks :)

FILE FORMAT:
(NAME:DATE:STATION NUMBER)

a01:01-24-2011:s1

a03:01-24-2011:s2

a03:09-24-2011:s1

a03:10-23-2011:s1

a04:11-01-2011:s1

a04:11-02-2011:s2

a04:11-03-2011:s1

a04:01-01-2011:s1

Upvotes: 0

Views: 85

Answers (1)

Henry Keiter
Henry Keiter

Reputation: 17168

Your dictionaries only hold {0:1} because that's all you're putting in them!

station1[0]=1 # This sets a key-value pair of 0 : 1

I'm not totally sure what your expected output is, but I think you're making this harder than it needs to be. I'm guessing you want something like this:

name, date, station = line.split(':') # use meaningful identifiers!

if name not in station1 and station == 's1':
    station1[name] = date
elif name not in station2 and station == 's2':
    station2[name] = date

This will give you output dictionaries like this:

{'a01' : '01-24-2011',
 'a03' : '09-24-2011'}

Note that by checking if the keys are already in the dictionary, you'll only add the first of any non-unique keys you come across to any given dictionary (for example, you'd only get the first two of your four 'a04' entries in your example input--the second two would be ignored, because 'a04' is already in both dicitonaries).

Upvotes: 1

Related Questions