Dictionary duplicate problem

Hi there,

May I know why I can’t use my code to return the dictionary in #307-3 ?

Screen Link:
Learn About The Mode And When To Use It | Dataquest

My Code:

value_counts = {}
def mode(array):
    counts = {}
    
    for value in array:
        if value in counts:
            counts[value] += 1
        else:
            counts[value] = 1
    value_counts = counts.copy()
    return max(counts, key = counts.get)

What I expected to happen:

value_counts  ==  counts

What actually happened:

value_counts == {}

This can be tricky to understand at first.

If you have

a = [1, 2, 3]
b = a

b[0] = 4

After running the above code, both a and b will be [4, 2, 3]. When you do b = a, b is referencing the same object. So, any changes made to b are made to a as well.

If you do

b = a.copy()

The above creates a shallow copy where b is a different object. Changes made to b don’t change a.

The same should happen with your dictionary as well, as you thought it would.

However, you use copy() inside your function which has a different scope. So, when you use

value_counts = counts.copy()

That creates a new object value_counts whose scope is limited to the function only. As a result, the value_counts object defined outside the function is unaffected.

1 Like

Thank you so much for these details : )

1 Like