Swift Dictionary Get Key For Value

Swift dictionary get key for value

Swift 3: a more performant approach for the special case of bijective dictionaries

If the reverse dictionary lookup use case covers a bijective dictionary with a one to one relationship between keys and values, an alternative approach to the collection-exhaustive filter operation would be using a quicker short-circuiting approach to find some key, if it exists.

extension Dictionary where Value: Equatable {
func someKey(forValue val: Value) -> Key? {
return first(where: { $1 == val })?.key
}
}

Example usage:

let dict: [Int: String] = [1: "one", 2: "two", 4: "four"]

if let key = dict.someKey(forValue: "two") {
print(key)
} // 2

How can I get key's value from dictionary in Swift?

Use subscripting to access the value for a dictionary key. This will return an Optional:

let apple: String? = companies["AAPL"]

or

if let apple = companies["AAPL"] {
// ...
}

You can also enumerate over all of the keys and values:

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

for (key, value) in companies {
print("\(key) -> \(value)")
}

Or enumerate over all of the values:

for value in Array(companies.values) {
print("\(value)")
}

Swift Dictionary Get Key for Values

func findKeyForValue(value: String, dictionary: [String: [String]]) ->String?
{
for (key, array) in dictionary
{
if (array.contains(value))
{
return key
}
}

return nil
}

Call the above function which will return an optional String?

let drinks = ["Soft Drinks": ["Cocoa-Cola", "Mountain Dew", "Sprite"],
"Juice" :["Orange", "Apple", "Grape"]]

print(self.findKeyForValue("Orange", dictionary: drinks))

This function will return only the first key of the array which has the value passed.

How do I get the key at a specific index from a Dictionary in Swift?

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.

Find the key for a given value of a Dictionary element in Swift

It is not possible to get the key by its value, because multiple keys can have the same value. For example, if you make a dictionary like this

let dict = [
"a" : 7
, "b" : 3
, "c" : 11
, "d" : 7
, "e" : 3
, "f" : 11
]

and try to find the key of value 7, there would be two such keys - "a" and "d".

If you would like to find all keys that map to a specific value, you can iterate the dictionary like this:

let search = 7
let keys = dict // This is a [String:int] dictionary
.filter { (k, v) -> Bool in v == search }
.map { (k, v) -> String in k }

This produces keys of all entries that have the search value, or an empty array when the search value is not present in the dictionary.

Getting Key from Dict as String in Swift

It looks like you know your keys going in, in this example.

Here are a few ways you might recover your keys in a useful way, though:

Say you have a dictionary

var dict: [String: Int] = ...

You could get the array of keys:

let keys = dict.keys // keys is of type [String]

You can iterate over keys and values:

for (key, value) in dict {
...
}

You can merge dictionaries of and choose values from either dictionary when keys collide:

let mergedDict = dict.merge(otherDict) { leftValue, rightValue in 
return leftValue
}

Addressing a version of your original question briefly:

Say you have the value for a certain key:

let donutValue = dict["DONUT"]

and somewhere else, where you lo longer have access to the key, you want to recover it from the value somehow. The best you could do is attempt to find the key by searching through the dictionary with the value you have.

var searchResult = dict.first { key, value in
return value == donutValue
}

This assumes the values in your dictionary are Equatable. Otherwise, you have to write some function or logic to figure out whether or not you've found that value in the dictionary corresponding to donutValue.

getting the value of a selected key in a dictionary swift

You can get the code as below,

if let codeDict = self.downloadPhotosData()[action.title!] as? [String: String] {
print(codeDict["code"]!)
}

Determining if Swift dictionary contains key and obtaining any of its values

You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key] you know whether the dictionary contains the key, because the Optional that you get back is not nil (and it contains the value).

So, if you just want to answer the question whether the dictionary contains the key, ask:

let keyExists = dict[key] != nil

If you want the value and you know the dictionary contains the key, say:

let val = dict[key]!

But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:

if let val = dict[key] {
// now val is not nil and the Optional has been unwrapped, so use it
}

How to get the key, value and index in a Dictionary loop?

Dictionaries are unordered, so all you can do is to enumerate through the dictionary, like this:

func getKeyValueIndex() {
if let myDict = myDict {
for (index, dict) in myDict.enumerated() { print(index, dict.key, dict.value) }
}
}


Related Topics



Leave a reply



Submit