0

I am trying to find the maximum value(s) in a dictionary and my approach is to iterate through and check for the greatest values and make a list of the greatest value/key pair and anything equivelent to it from a dictionary and I have the following...

def foo(class_sum, input_object):  # Predicts the class x is a member of given probability dictionary
    probabilities = calc_class_probs(class_sum, input_object)  # Returns a dictionary with probability elements
    best_label, best_perc = list(), list()
    best_perc.append(-1)
    print(best_perc[0])
    for val in probabilities:
        print(probabilities[val])
        if probabilities[val] > best_perc[0]:
            del best_label
            del best_perc  # Empty list in case unwanted elements are present
            best_label, best_perc = val, probabilities[val]  # update with new best
        elif probabilities[val] == best_perc:
            best_label.append(val)
            best_perc.append(probabilities[val])

    return best_label, best_perc

So from this I expect that if probabilities[val] > best_perc[0]: will evaluate to 7.591391076586993e-36 > -1, at least for the first iteration. However I get the following output from the print statements...

-1
7.591391076586993e-36

EDIT: it appears to fail on the second iteration, could this be due to the del statements?

0 7.591391076586993e-36
1 7.297754873023128e-36
...
IndexError: invalid index to scalar variable.

and this error...

if probabilities[val] > best_perc[0]:
IndexError: invalid index to scalar variable.

Why can it print the values but not index them here? Please note probabilities is a dictionary with keys that have single probability values like the below.

{'0': 7.59139e-36, '1': 7.2977e-36,...}

1 Answer 1

2

I believe your problem is here:

best_label, best_perc = val, probabilities[val]

After executing first 'if' best_lavel and best_perc is no longer list, so you cant access best_perc[0].

You can replace it by

best_label, best_perc = [val], [probabilities[val]]

Notice, when you iterate in a dictionary, you iterate through keys, not values. You can alos iterate by keys and values:

for key, val in dictionary.items():
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the tip about iterating through dictionaries, solved and improved my code!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.