In this post, we will see how to resolve Get max value from every index in a dictionary in python
Question:
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.
Get max value from every index, Best Answer:
Only write what you say.[code]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)
[/code]
[code]{(1, 1, True): 0, (2, 1, True): 0, (1, 2, True): 1, (2, 2, True): 0}
[/code]
If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com