Ignacio Such
Ignacio Such

Reputation: 129

Get max value from every index in a dictionary in python

I was wondering how to get the max value from every key from a dictionary. Let's say I have this:

dict={(1,1,True):[-1, 0.26], (2,1,True):[0.1, 0],(1,2,True):[0.01, -1],(2,2,True):[1, -0.11],}

And this is the expected output:

new_dict={(1,1,True):0, (2,1,True):0,(1,2,True):1,(2,2,True):0,}

The new 0 and 1 values means the following:

Upvotes: 0

Views: 69

Answers (2)

I'mahdi
I'mahdi

Reputation: 24049

Only write what you say.

dct={
    (1,1,True):[-1, 0.26], 
    (2,1,True):[0.1, 0],
    (1,2,True):[0.01, -1],
    (2,2,True):[1, -0.11],
}

for key, value in dct.items():
    # check 'abs(item_zero) with 'abs(item_one)' as 'boolean' 
    # then convert 'False -> 0' and 'True -> 1'.
    dct[key] = int(abs(value[0]) <= abs(value[1]))
print(dct)

Output:

{(1, 1, True): 0, (2, 1, True): 0, (1, 2, True): 1, (2, 2, True): 0}

Upvotes: 1

ShlomiF
ShlomiF

Reputation: 2895

You can write a simple argmax function, and do the rest with simple list/dict comprehensions.

def argmax(lst):
    return max(range(len(lst)), key=lambda i: lst[i])


my_dict = {(1, 1, True): [-1, 0.26], (2, 1, True): [0.1, 0], (1, 2, True): [0.01, -1], (2, 2, True): [1, -0.11], }
print({k: argmax([abs(v_) for v_ in v]) for k, v in my_dict.items()})

Note: It's not a good idea to override dict...

You can also maybe make things cleaner by putting the abs inside the argmax function:

def abs_argmax(lst):
    return max(range(len(lst)), key=lambda i: abs(lst[i]))


my_dict = {(1, 1, True): [-1, 0.26], (2, 1, True): [0.1, 0], (1, 2, True): [0.01, -1], (2, 2, True): [1, -0.11], }
print({k: abs_argmax(v) for k, v in my_dict.items()})

Upvotes: 1

Related Questions