So, say I have a dictionary that looks like this:
var data : [Float:Float] = [0:0,1:1,2:1.414,3:2.732,4:2,5:5.236,6:3.469,7:2.693,8:5.828,9:3.201]
How would I programmatically find the highest value in the dictionary? Is there a "data.max" command or something?
To find the largest number in an array in Swift, call max() method. max() method returns the maximum of the elements present in the array.
The easiest way to find the minimum or maximum values in a Python dictionary is to use the min() or max() built-in functions applied to the list returned by the dictionary values() method.
Python find highest value in dictionary By using the built-in max() method. It is provided with the 'alpha_dict' variable to obtain the highest value from and to return the key from the given dictionary with the highest value, the dict. get() method is used.
max() Return Value The max() method returns the maximum element of dictionary . Note: If dictionary is empty, the method returns nil .
let maximum = data.reduce(0.0) { max($0, $1.1) }
Just a quick way using reduce
.
or:
data.values.max()
Output:
print(maximum) // 5.828
A Swift Dictionary provides the max(by:) method. The Example from Apple is as follows:
let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] let greatestHue = hues.max { a, b in a.value < b.value } print(greatestHue) // Prints "Optional(("Heliotrope", 296))"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With