Chris Koknat
Chris Koknat

Reputation: 3451

Sort dictionary keys by value, then by key

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

Upvotes: 6

Views: 3380

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236360

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)
}

Upvotes: 11

Code Different
Code Different

Reputation: 93161

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.

Upvotes: 2

Related Questions