I'd like to iterate over the keys of a dictionary, sorted first by value (descending), and then by key (ascending)let dict = ["foo" : 1, "bar" : 1, "baz" : 2, "qux" : 2]
The order of the iteration should be:["baz", "qux", "bar", "foo"]
I'd like to print:
baz 2
qux 2
bar 1
foo 1
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
We can sort a dictionary with the help of a for loop. First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these key-value pairs in the sorted order into a new dictionary.
Xcode 13.2.1 • Swift 5.5.2
extension Dictionary where Key: Comparable, Value: Comparable {
var valueKeySorted: [(Key, Value)] {
sorted {
$0.value != $1.value ?
$0.value > $1.value :
$0.key < $1.key
}
}
}
let dict = ["foo" : 1, "bar" : 1, "baz" : 2, "qux" : 2]
let keyValueArray = dict.valueKeySorted
print(keyValueArray) // "[("baz", 2), ("qux", 2), ("bar", 1), ("foo", 1)]"
for (key, value) in keyValueArray {
print(key, value)
}
Try this:
let dict = ["foo" : 1, "bar" : 1, "baz" : 2, "qux" : 2]
let result = dict.map { (key: $0.0, value: $0.1) }
.sort {
if $0.value != $1.value {
return $0.value > $1.value
}
return $0.key < $1.key
}
for r in result {
print("\(r.key) \(r.value)")
}
map
transforms the dictionary into an array of tuples (key: "foo", value: 1)
etc. It then becomes a matter of sorting that array with sort
.
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