How to get keys and values from dictionary in same order?

410 views Asked by At

I am using a dictionary to store key-value pairs. It's storing correctly kay-value pair. But when I try to retrieve all keys and all values separately, it's printing different differently.

Here is the example,

    var sampleDic:[String:Any] = [:]
    sampleDic["one"] =  1
    sampleDic["two"] =  2
    sampleDic["three"] =  3

    print("keys: \(sampleDic.keys)")
    print("Values: \(sampleDic.values)")

sometimes its prints,

 keys: ["one", "two", "three"]
 Values: [1, 2, 3]

and sometimes its prints,

keys: ["three", "one", "two"]
Values: [3, 1, 2]

each time, whenever I run the code, I will get different output.

How I can get the output in the same sequence for keys and values always. Both keys and values must be printed in array bases on which key/value they stored in the dictionary.

If this is not possible with dictionaries, then is there an alternative way to store and get values like this?

1

There are 1 answers

2
Sweeper On

Dictionaries stores mappings between keys and values, not a list of key value pairs, so there is no order.

If you want an order, you can give it one by sorting the key value pairs, e.g. by the keys

ket kvp = Array(sampelDic).sorted { $0.key < $1.key }

This produces a [(String, Any)]. If you actually want a [String] and a [Any], you can write an unzip function (from answer by Rob):

func unzip<K, V>(_ array: [(key: K, value: V)]) -> ([K], [V]) {
    var keys = [K]()
    var values = [V]()

    keys.reserveCapacity(array.count)
    values.reserveCapacity(array.count)

    array.forEach { key, value in
        keys.append(key)
        values.append(value)
    }

    return (keys, values)
}

Now you can do:

let (keys, values) = unzip(kvp)
print("Keys:", keys)
print("Values:", values)