How can I check if a key exists in a dictionary? My dictionary is of type [Type:Type?]
.
I can't simply check dictionary[key] == nil
, as that could result from the value being nil
.
Any ideas?
How do you check if a key exists or not in a dictionary? You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key(). 2.
The simplest way to check if a key exists in a dictionary is to use the in operator. It's a special operator used to evaluate the membership of a value. This is the intended and preferred approach by most developers.
To get the value for the key, use dict[key] . dict[key] raises an error when the key does not exist, but the get() method returns a specified value (default is None ) if the key does not exist.
Actually your test dictionary[key] == nil
can be used to check if a key exists in a dictionary. It will not yield true
if the value is set to nil
:
let dict : [String : Int?] = ["a" : 1, "b" : nil] dict["a"] == nil // false, dict["a"] is .Some(.Some(1)) dict["b"] == nil // false !!, dict["b"] is .Some(.None) dict["c"] == nil // true, dict["c"] is .None
To distinguish between "key is not present in dict" and "value for key is nil" you can do a nested optional assignment:
if let val = dict["key"] { if let x = val { println(x) } else { println("value is nil") } } else { println("key is not present in dict") }
I believe the Dictionary type's indexForKey(key: Key)
is what you're looking for. It returns the index for a given key, but more importantly for your proposes, it returns nil if it can't find the specified key in the dictionary.
if dictionary.indexForKey("someKey") != nil { // the key exists in the dictionary }
Swift 3 syntax....
if dictionary.index(forKey: "someKey") == nil { print("the key 'someKey' is NOT in the dictionary") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With