0

Can someone explain why my code is returning no match as I thought you can compare two dictionaries with "=="?

 import csv
 import sys
 import copy

 def main():
     # TODO: Check for command-line usage
     if len(sys.argv) != 3:
        sys.exit(1)
     # TODO: Read database file into a variable
     database = []
     key = []
     database_file = sys.argv[1]
     d = open(database_file, "r")
     reader = csv.DictReader(d)
     for name in reader:
         database.append(name)
     copy_database = copy.deepcopy(database)
     for i in range(len(copy_database)):
         del copy_database[i]["name"]
     for i in range(len(copy_database)):
         for k in copy_database[i]:
             key.append(k)
     remove_dup = list(set(key))

     # TODO: Read DNA sequence file into a variable
     sequence_file = sys.argv[2]
     s = open(sequence_file, "r")
     sequence = s.read()
     # TODO: Find longest match of each STR in DNA sequence
     match = {}
     for i in range(len(remove_dup)):
         match[remove_dup[i]] = longest_match(sequence,remove_dup[i])

     # TODO: Check database for matching profiles
     for i in range(len(database)):
         if match == copy_database[i]:
            print(database[i]["name"])
     print("No Match")

I can see that i am putting the longest sequence in the match dict and it is the correct one but when im trying to compare it with the database copy without the name key im not getting any hits.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 2
    Please repost your code with proper indentation. Indentaiton is critical in python. See https://stackoverflow.com/help/formatting – Barmar Aug 03 '23 at 16:26
  • `print("No Match")` doesn't seem to be in a conditional, so it will be printed all the time. See https://stackoverflow.com/questions/42913798/searching-array-reports-not-found-even-though-its-found/42913882#42913882 – Barmar Aug 03 '23 at 16:27
  • Thanks for you tips. I've indented the code. What i am curious about is this line here:if match == copy_database[i]: where match is a dict and copy_database[i] is a dict from a list. I am correct to assume that this would compare the two dicts key value with paired value regardless of sortation and return true or false? – fumitsukai Aug 03 '23 at 17:33
  • The `def` body isn't indented. – Barmar Aug 03 '23 at 17:34
  • Yes, that's how it compares dictionaries. See https://stackoverflow.com/questions/17217225/what-does-the-operator-actually-do-on-a-python-dictionary – Barmar Aug 03 '23 at 17:36
  • Get out of the habit of using `for index in range(len(list)):`. Use `for item in list:` or `for index, item in enumerate(list):` – Barmar Aug 03 '23 at 17:36
  • As I said above, your program always prints "No match" no matter what happened in the comparison loop. – Barmar Aug 03 '23 at 17:38
  • 1
    Thanks for the tips. Got it to work in the end. the match dict had int values while the database had text. – fumitsukai Aug 03 '23 at 18:05

0 Answers0