-1

I have been trying to do a linear search on a csv file and have written a simple algorithm to do so. It should print the amount of lines searched and the information

 import csv
 count = 1
 with open('UKDATA.csv') as csvfile: #This opens the file as a csv file
     reader = csv.DictReader(csvfile) 
     for row in reader:              
        first_name = row["first_name"]
        last_name = row["last_name"]
        if first_name == "Alethea" and last_name == "Mould" :
            print(count, "rows searched")
            print("Alethea Mould found on line",count+1)
            print(row)
            break
        count += 1

Everytime I run this code it print out the information in a different order. Why does it do this Thanks

donkopotamus
  • 18,536
  • 2
  • 36
  • 52

1 Answers1

0

Presumably you mean that it prints out the row fields in a different order during the statement

print(row)

Why? You have created reader as a DictReader meaning that it returns each line as a dictionary. Dictionaries do not promise any ordering of keys.

If you wish it to be printed in a correct order, then you may use something like:

print([row[k] for k in reader.fieldnames])
donkopotamus
  • 18,536
  • 2
  • 36
  • 52