17. The most Frequent Value task on Condition Statement Problem: Help me review some code

Screen Link:

This is the seventh task in Condition Statement problem series
I’m using the dic() type to solve this task, but here are some errors I met
My Code:

values = [72, 50, 48, 50, 7, 66, 62, 32, 33, 75, 30, 85, 6, 85, 82, 88, 30, 32, 78, 39, 57, 96, 45, 57, 61, 32, 10, 62, 48, 32, 96, 75, 15]

check_list = {}
for i in values:
    if i in check_list:
        check_list[i] += 1
        check_list[i] = 1
for j in list(check_list):
    for k in range(len(list(check_list))):
        maximum = check_list[list(check_list)[k]]
        position = 0
        if check_list[j] > maximum:
            maximum = check_list[j]
            position = j
print(maximum, position)

I’m expecting the result is 32:4, but actually is

What actually happened:

1 0

I’ve been put it to Python Tutor but they’re warning me out of step
I thought that at a maximum value that I’ve set got something wrong but I still have not found another good way to set it
Could you let me know how I can deal with the maximum value above in my code??

There are many ways to solve this problem with the check_list dictionary.

The first way is to use the max function with the check list dictionary. You iterate with a for-loop like this:

for key, value in check_list.items():
    if key == max(check_list, key=check_list.get):
        most_frequent, freq = key, value

The if statement checks for the maximum value, and if true, the next step assign the key and value to most_frequent, and freq.

Similarly, the above step can be completed using list comprehension:

[(key, value) for (key, value) in check_list.items() if key == max(check_list, key=check_list.get)]

Another way to solve this is using Counter.

from collections import Counter

most_frequent, freq = Counter(values).most_common(1)[0]
1 Like

Let me guest about method 1: for loop

We will work on the different views of the original check_list dictionary where we can directly work with key&value => we use dict.items() as an iterable variable in for loop
In this code, dict.get() operation as when we order value in random key like dict[key] but in larger area, right?
Max function here in type: Max(iterable, [key]) with key is the value we want to find out which is max

As my explanation about the code, is it right??

max(check_list) returns 96. The max function returns the largest key in check_list dictionary.

max(check_list, key=check_list.get) returns the key with the largest value pair.

max(check_list.items(), key=lambda x: x[1])

Here you are trying to find the maximum of (key, value) pairs. You find the maximum with either the keys (key = lambda x: x[0]) or values (key = lambda x: x[1]).