I want to insert a key with a corresponding value in an existing dictionary...
I am able to set values for existing keys in the dictionary, but I am not able to add a new key value...
Any help would be appreciated.
You can add key to dictionary in python using mydict["newkey"] = "newValue" method. Dictionaries are changeable, ordered, and don't allow duplicate keys. However, different keys can have the same value.
Use NSMutableDictionary
NSMutableDictionary *yourMutableDictionary = [NSMutableDictionary alloc] init];
[yourMutableDictionary setObject:@"Value" forKey:@"your key"];
Update for Swift:
The following is the exact swift replica for the code mentioned above
var yourMutableDictionary = NSMutableDictionary()
yourMutableDictionary.setObject("Value", forKey: "Key")
But i would suggest you to go with Swift Dictionary way.
var yourMutableDictionary = [String: AnyObject]() //Open close bracket represents initialization
//The reason for AnyObject is a dictionary's value can be String or
//Array or Dictionary so it is generically written as AnyObject
yourMutableDictionary["Key"] = "Value"
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
By using this method we can add the new value to NSMutableDictionary
[dict setObject:@"Value" forKey:@"Key"];
To know wheather the key exist in dictionary
[[dict allKeys] containsObject:@"key"];
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