290

I have a simple Dictionary which is defined like:

var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]

Now I want to add an element into this dictionary: 3 : "efg"

How can I append 3 : "efg" into this existing dictionary?

2
  • use NSMutableDictionary Commented Dec 5, 2014 at 10:09
  • 2
    Are you sure you want a dictionary and not an array, since your keys seem to be the numbers 1, 2 and 3?
    – gnasher729
    Commented Jan 15, 2016 at 15:51

20 Answers 20

292

You're using NSDictionary. Unless you explicitly need it to be that type for some reason, I recommend using a Swift dictionary.

You can pass a Swift dictionary to any function expecting NSDictionary without any extra work, because Dictionary<> and NSDictionary seamlessly bridge to each other. The advantage of the native Swift way is that the dictionary uses generic types, so if you define it with Int as the key and String as the value, you cannot mistakenly use keys and values of different types. (The compiler checks the types on your behalf.)

Based on what I see in your code, your dictionary uses Int as the key and String as the value. To create an instance and add an item at a later time you can use this code:

var dict = [1: "abc", 2: "cde"] // dict is of type Dictionary<Int, String>
dict[3] = "efg"

If you later need to assign it to a variable of NSDictionary type, just do an explicit cast:

let nsDict = dict as! NSDictionary

And, as mentioned earlier, if you want to pass it to a function expecting NSDictionary, pass it as-is without any cast or conversion.

3
  • Thanks for a proper explanation of what a person should actually do. Utilizing the convenience of Swift to create and manipulate a Dictionary object and then converting it to NSDictionary at the end if you need to. Wonderful. Thanks. Commented Mar 30, 2016 at 1:23
  • Is there anyway that I can append to the same key using a delimiter (similar to addValue). I mean like add a "Antonio" to key 1 so dic[1] would return "abc, Antonio".
    – mfaani
    Commented Nov 17, 2016 at 14:40
  • @honey not that I am aware of... but it's a simple append if the element already exists
    – Antonio
    Commented Nov 18, 2016 at 10:52
143

you can add using the following way and change Dictionary to NSMutableDictionary

dict["key"] = "value"
7
  • 2
    I got an error which says Cannot assign to the result of this expression Commented Dec 5, 2014 at 10:08
  • add this way for your question dict[3] = "efg"; Commented Dec 5, 2014 at 10:10
  • check my edited answer its working for me.change dictionary to Mutable one it works! Commented Dec 5, 2014 at 10:12
  • 1
    dict["testval"] = "test".. Error fatal error: unexpectedly found nil while unwrapping an Optional value
    – jose920405
    Commented Jul 24, 2015 at 15:32
  • 2
    It won't work with 2.2+ , dict is readonly in that expression
    – jeveloper
    Commented Jun 4, 2016 at 17:26
90

I know this might be coming very late, but it may prove useful to someone. So for appending key value pairs to dictionaries in swift, you can use updateValue(value: , forKey: ) method as follows :

var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)
1
  • 1
    Thank you! I kept getting something about a missing default parameter when I was trying to add new values to the dict. This method worked.
    – chaytan
    Commented Jul 2, 2020 at 18:55
64

SWIFT 3 - XCODE 8.1

var dictionary =  [Int:String]() 

dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)

So, your dictionary contains:

dictionary[1: Hola, 2: Hello, 3: Aloha]

7
  • 8
    How is this better than dictionary[1] = "Hola"?
    – Ky -
    Commented Dec 19, 2016 at 22:26
  • 3
    Is simply another way to do it. All depend of what do you need do ! I my case, this is the best way Commented Dec 21, 2016 at 13:52
  • 4
    I understand that you think this is better; that's why you posted it. But I don't see how this is better. Please, tell me how this is better
    – Ky -
    Commented Dec 21, 2016 at 19:46
  • I agree there should be a method called "addValue" or "setValue", that "updateValue" should be used for UPDATING as its name says
    – pkarc
    Commented Feb 10, 2017 at 18:34
  • The reason is that when the dictionary was init be has a value [] that is different to nil, so is necessary use the property updateValue because we are trying change the value and not insert it. Commented Feb 14, 2017 at 20:11
24

If your dictionary is Int to String you can do simply:

dict[3] = "efg"

If you mean adding elements to the value of the dictionary a possible solution:

var dict = Dictionary<String, Array<Int>>()

dict["key"]! += [1]
dict["key"]!.append(1)
dict["key"]?.append(1)
0
19

Swift 3+

Example to assign new values to Dictionary. You need to declare it as NSMutableDictionary:

var myDictionary: NSMutableDictionary = [:]
let newValue = 1
myDictionary["newKey"] = newValue
print(myDictionary)
15
For whoever reading this for swift 5.1+

  // 1. Using updateValue to update the given key or add new if doesn't exist


    var dictionary = [Int:String]()    
    dictionary.updateValue("egf", forKey: 3)



 // 2. Using a dictionary[key]

    var dictionary = [Int:String]()    
    dictionary[key] = "value"



 // 3. Using subscript and mutating append for the value

    var dictionary = [Int:[String]]()

    dictionary[key, default: ["val"]].append("value")
14

Given two dictionaries as below:

var dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]

Here is how you can add all the items from dic2 to dic1:

dic2.forEach {
   dic1[$0.key] = $0.value
}
2
  • 10
    It's better to use .forEach instead of .map as we don't need any return mapped array Commented Jun 19, 2016 at 12:11
  • To be more clear, this can be dic2.map { dic1[$0.key] = $0.value } Commented Jul 15, 2020 at 21:03
12

In Swift, if you are using NSDictionary, you can use setValue:

dict.setValue("value", forKey: "key")
1
  • 2
    edited your answer, in the future consider adding more info to avoid downvotes.
    – Juan Boero
    Commented Feb 5, 2016 at 21:47
12

[String:Any]

For the fellows using [String:Any] instead of Dictionary below is the extension

extension Dictionary where Key == String, Value == Any {
    
    mutating func append(anotherDict:[String:Any]) {
        for (key, value) in anotherDict {
            self.updateValue(value, forKey: key)
        }
    }
}
11

Dict.updateValue updates value for existing key from dictionary or adds new new key-value pair if key does not exists.

Example-

var caseStatusParams: [String: AnyObject] = ["userId" : UserDefault.userID ]
caseStatusParams.updateValue("Hello" as AnyObject, forKey: "otherNotes")

Result-

▿  : 2 elements
    - key : "userId"
    - value : 866
▿  : 2 elements
    - key : "otherNotes"
    - value : "Hello"
0
11

As of Swift 5, the following code collection works.

 // main dict to start with
 var myDict : Dictionary = [ 1 : "abc", 2 : "cde"]

 // dict(s) to be added to main dict
 let myDictToMergeWith : Dictionary = [ 5 : "l m n"]
 let myDictUpdated : Dictionary = [ 5 : "lmn"]
 let myDictToBeMapped : Dictionary = [ 6 : "opq"]

 myDict[3]="fgh"
 myDict.updateValue("ijk", forKey: 4)

 myDict.merge(myDictToMergeWith){(current, _) in current}
 print(myDict)

 myDict.merge(myDictUpdated){(_, new) in new}
 print(myDict)

 myDictToBeMapped.map {
     myDict[$0.0] = $0.1
 }
 print(myDict)
1
  • This is the most exhaustive answer. Thanks!
    – Danil
    Commented Apr 3, 2023 at 17:11
10

To add new elements just set:

listParameters["your parameter"] = value
8

There is no function to append the data in dictionary. You just assign the value against new key in existing dictionary. it will automatically add value to the dictionary.

var param  = ["Name":"Aloha","user" : "Aloha 2"]
param["questions"] = "Are you mine?"
print(param)

The output will be like

["Name":"Aloha","user" : "Aloha 2","questions" : ""Are you mine"?"]

5

To append a new key-value pair to a dictionary you simply have to set the value for the key. for eg.

// Initialize the Dictionary
var dict = ["name": "John", "surname": "Doe"]
 
// Add a new key with a value

dict["email"] = "[email protected]"

print(dict)

Output -> ["surname": "Doe", "name": "John", "email": "[email protected]"]

3
var dict = ["name": "Samira", "surname": "Sami"]
// Add a new enter code herekey with a value
dict["email"] = "[email protected]"
print(dict)
2
  • 1
    Please provide some information why this answer solves the problem Commented Nov 22, 2016 at 19:03
  • @StephenReindl If you run it, you'll see ;)
    – Ky -
    Commented Dec 19, 2016 at 22:39
0

Up till now the best way I have found to append data to a dictionary by using one of the higher order functions of Swift i.e. "reduce". Follow below code snippet:

newDictionary = oldDictionary.reduce(*newDictionary*) { r, e in var r = r; r[e.0] = e.1; return r }

@Dharmesh In your case, it will be,

newDictionary = dict.reduce([3 : "efg"]) { r, e in var r = r; r[e.0] = e.1; return r }

Please let me know if you find any issues in using above syntax.

0
0

Swift 5 happy coding

var tempDicData = NSMutableDictionary()

for temp in answerList {
    tempDicData.setValue("your value", forKey: "your key")
}
-1

I added Dictionary extension

extension Dictionary {   
  func cloneWith(_ dict: [Key: Value]) -> [Key: Value] {
    var result = self
    dict.forEach { key, value in result[key] = value }
    return result  
  }
}

you can use cloneWith like this

 newDictionary = dict.reduce([3 : "efg"]) { r, e in r.cloneWith(e) }
1
  • You don't need to clone a dictionary. Dictionary is a value type in Swift.
    – nuynait
    Commented Nov 5, 2021 at 17:58
-11

if you want to modify or update NSDictionary then first of all typecast it as NSMutableDictionary

let newdictionary = NSDictionary as NSMutableDictionary

then simply use

 newdictionary.setValue(value: AnyObject?, forKey: String)

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