Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dictionary keys by value, then by key

Tags:

swift

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
like image 314
Chris Koknat Avatar asked Nov 23 '15 22:11

Chris Koknat


People also ask

Can you sort a dictionary based on keys?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.

How do you sort a dictionary with respect to 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.


2 Answers

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)
}
like image 106
Leo Dabus Avatar answered Oct 21 '22 01:10

Leo Dabus


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.

like image 28
Code Different Avatar answered Oct 21 '22 01:10

Code Different