143

I have a Dictionary in Swift and I would like to get a key at a specific index.

var myDict : Dictionary<String,MyClass> = Dictionary<String,MyClass>()

I know that I can iterate over the keys and log them

for key in myDict.keys{

    NSLog("key = \(key)")

}

However, strangely enough, something like this is not possible

var key : String = myDict.keys[0]

Why ?

2
  • 12
    Just so you know, Swift dictionaries are not guaranteed to be in any specific order. So you can't expect for sure that the keys to be indexed in the order you put them in.
    – radex
    Jul 8, 2014 at 22:11
  • +1 @radex and also would like to add, if possible, a source to read more about your statement would be greatly appreciated.
    – S.H.
    Nov 7, 2014 at 21:09

10 Answers 10

244

That's because keys returns LazyMapCollection<[Key : Value], Key>, which can't be subscripted with an Int. One way to handle this is to advance the dictionary's startIndex by the integer that you wanted to subscript by, for example:

let intIndex = 1 // where intIndex < myDictionary.count
let index = myDictionary.index(myDictionary.startIndex, offsetBy: intIndex)
myDictionary.keys[index]

Another possible solution would be to initialize an array with keys as input, then you can use integer subscripts on the result:

let firstKey = Array(myDictionary.keys)[0] // or .first

Remember, dictionaries are inherently unordered, so don't expect the key at a given index to always be the same.

10
  • 3
    Probably faster would be Array(myDict)[0].0 since it wouldn't copy the keys array, and shouldn't copy the internal structures of the dictionary, although it might. Jul 8, 2014 at 20:37
  • 7
    Keep in mind that there are no promise about which key this will return, but good note about the "view" type that is returned. Deleted my answer since it didn't actually apply to the question.
    – Rob Napier
    Jul 8, 2014 at 21:16
  • 11
    To clarify what Rob is saying, while it may seem like the keys are always ordered the same every time, this is not the case and is simply an implementation detail. It's very possible that you could add the key "foo" and the internal representation will completely reorder the dictionary. A dictionary is an unordered collection of key-value pairs. Therefore, the answer above is making dangerous assumptions that do not hold true. Jul 8, 2014 at 21:53
  • 9
    If you need the keys in a specific order, keep an array of them. Then you can use them like myDict[keysArray[0]]. Jul 8, 2014 at 23:08
  • 1
    Doesn't work... 'NSDictionary' is not convertible to '_ArrayBuffer<T>'
    – Chris
    Mar 7, 2015 at 19:12
70

Swift 3 : Array() can be useful to do this .

Get Key :

let index = 5 // Int Value
Array(myDict)[index].key

Get Value :

Array(myDict)[index].value
4
  • This works for me for Swift 3. Don't understand why the created Array is re-arranged though. Any thoughts? May 11, 2017 at 20:16
  • Thanks this helped me
    – ANE
    Aug 2, 2017 at 12:11
  • 1
    @josef What about it is counter intuitive? Dictionaries are key, value pairs, so the idea of an index doesn't fix. Arrays are accessed by index, so this turns a dictionary INTO an Array, and then accesses the array by it's index. A dictionary like ["a": 1, "b": 2], can be turned into an array of dictionaries like [[key: "a", value: 1], [key: "b", value: 2]], this can then be accessed by index.
    – Peter R
    Mar 24, 2018 at 8:34
  • Thanks, the way is to convert it to array first. But it is really annoying when apply it in real project. Like this one cell.artwork.image = Array(albumDict)[indexPath.item].value.first?.artwork?.image, I use this shit long chain just to get a value from the values.
    – Zhou Haibo
    Jun 25, 2021 at 7:24
29

Here is a small extension for accessing keys and values in dictionary by index:

extension Dictionary {
    subscript(i: Int) -> (key: Key, value: Value) {
        return self[index(startIndex, offsetBy: i)]
    }
}
2
  • 3
    'advance' API has been removed in Swift 2.0 use -- self[self.startIndex.advancedBy(i)] --
    – Romain
    Jan 24, 2016 at 16:01
  • 3
    @TomSawyer dictionaries aren't ordered.
    – Hedylove
    Jul 1, 2019 at 7:36
11

You can iterate over a dictionary and grab an index with for-in and enumerate (like others have said, there is no guarantee it will come out ordered like below)

let dict = ["c": 123, "d": 045, "a": 456]

for (index, entry) in enumerate(dict) {
    println(index)   // 0       1        2
    println(entry)   // (d, 45) (c, 123) (a, 456)
}

If you want to sort first..

var sortedKeysArray = sorted(dict) { $0.0 < $1.0 }
println(sortedKeysArray)   // [(a, 456), (c, 123), (d, 45)]

var sortedValuesArray = sorted(dict) { $0.1 < $1.1 }
println(sortedValuesArray) // [(d, 45), (c, 123), (a, 456)]

then iterate.

for (index, entry) in enumerate(sortedKeysArray) {
    println(index)    // 0   1   2
    println(entry.0)  // a   c   d
    println(entry.1)  // 456 123 45
}

If you want to create an ordered dictionary, you should look into Generics.

2
  • 1
    what if i wanted to search for what the index was for a equal to 456?
    – Famic Tech
    Jul 31, 2018 at 3:06
  • 2
    @Max, this is old Swift syntax. Now you can use: dict.enumerated().forEach { (index, element) in ... } Jan 15, 2019 at 10:28
10

From https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/CollectionTypes.html:

If you need to use a dictionary’s keys or values with an API that takes an Array instance, initialize a new array with the keys or values property:

let airportCodes = [String](airports.keys) // airportCodes is ["TYO", "LHR"]   
let airportNames = [String](airports.values) // airportNames is ["Tokyo", "London Heathrow"]
7

SWIFT 3. Example for the first element

let wordByLanguage = ["English": 5, "Spanish": 4, "Polish": 3, "Arabic": 2]

if let firstLang = wordByLanguage.first?.key {
    print(firstLang)  // English
}
1
  • 4
    What if i wanted to get the index where key is Polish?
    – Famic Tech
    Jul 31, 2018 at 3:07
7

In Swift 3 try to use this code to get Key-Value Pair (tuple) at given index:

extension Dictionary {
    subscript(i:Int) -> (key:Key,value:Value) {
        get {
            return self[index(startIndex, offsetBy: i)];
        }
    }
}
3

SWIFT 4


Slightly off-topic: But here is if you have an Array of Dictionaries i.e: [ [String : String] ]

var array_has_dictionary = [ // Start of array

   // Dictionary 1

   [ 
     "name" : "xxxx",
     "age" : "xxxx",
     "last_name":"xxx"
   ],

   // Dictionary 2

   [ 
     "name" : "yyy",
     "age" : "yyy",
     "last_name":"yyy"
   ],

 ] // end of array


cell.textLabel?.text =  Array(array_has_dictionary[1])[1].key
// Output: age -> yyy
3
  • 1
    How can I get the index of the item that has age = xxxx in your example?
    – Famic Tech
    Jul 31, 2018 at 3:10
  • 1
    arrayIndex = 0, ageDictIndex = 1, Array(array_has_dictionary[arrayIndex].keys)[ageDictIndex] = xxxx
    – Kristian
    Aug 27, 2018 at 21:57
  • @FamicTech, Kris answered your question
    – Suhaib
    Aug 31, 2018 at 20:56
2

Here is an example, using Swift 1.2

var person = ["name":"Sean", "gender":"male"]
person.keys.array[1] // "gender", get a dictionary key at specific index 
person.values.array[1] // "male", get a dictionary value at specific index
0

I was looking for something like a LinkedHashMap in Java. Neither Swift nor Objective-C have one if I'm not mistaken.

My initial thought was to wrap my dictionary in an Array. [[String: UIImage]] but then I realized that grabbing the key from the dictionary was wacky with Array(dict)[index].key so I went with Tuples. Now my array looks like [(String, UIImage)] so I can retrieve it by tuple.0. No more converting it to an Array. Just my 2 cents.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.