Need help with my code (Functions Practice Problem #11)

Hi, may someone explain why my code doesn’t work?

Screen Link:

My Code:

from csv import reader
def check_unique_values(csv_filename, col_name):
    index = find_col_index(csv_filename, col_name)
    if index == -1:
        return None
    opened_file = open(csv_filename)
    read_file = reader(opened_file)
    rows = list(read_file)
    rows = rows[1:]
    dictionary = {}
    for row in rows:
        column = row[index]
        if column in dictionary: 
            dictionary[column] += 1
            dictionary[column] = 1
    for key in dictionary:
        value = dictionary[key]
        if value == 1:
            return True
        if value != 1:
            return False

What I expected to happen:
I expected the output to give me the following…

provided inputs

csv_filename = “users.csv”
col_name1 = “name”

answer to this input: False

col_name2 = “id”

answer to this input: True

col_name3 = “email”

answer to this input: False

What actually happened:

I got all three True’s for the output and it told me my answer submission was correct.

Can someone explain to me why my code for the for loop below didn’t return the right True/False answers?

for key in dictionary:
        value = dictionary[key]
        if value == 1:
            return True
        if value != 1:
            return False

I thought it would be counting the frequency of each key but it seems like it didn’t. Thank you so much in advance!

Click here to open the screen in a new tab.

This can be difficult to figure out, but the issue is with your statement here -

Let’s say you have a dictionary like the following -

{"abc": 1, "abd": 3}

Now, when you iterate over the above, for the first iteration, your value would be 1. And then your first if condition becomes True. And you return True. At this stage your code stops running. Because your function returned a value. So, you never actually reach that second key abd to say that your dictionary is not unique.

So, you need to modify your code so that you don’t return True right away. If you feel stuck, check out their provided solution as to how you could do that.



Thanks for the explanation! That makes a lot of sense. I saw the provided solution as well.

for key in freq:
        if freq[key] > 1:
            return False
return True

So pretty much in my code, I cannot have two “if” statements when I check whether the dictionary has a unique value.