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:
- If the absolute max value is the first element, the output value will be 0. If not, 1.
- Example: Abs(-1), Abs(0.26)-> 1>0.26 -> 0 will be the expected output.
CodePudding user response:
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}
CodePudding user response:
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()})