Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add a Dictionary of items into another Dictionary

People also ask

Can you put a dictionary in a dictionary?

Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples, but the key-values can be repeated and be of any type. Nested Dictionary: Nesting Dictionary means putting a dictionary inside another dictionary.

How do I create a nested dictionary?

You can create a nested dictionary in Python by placing comma-separated dictionaries within curly braces {}. A Python nested dictionary allows you to store and access data using the key-value mapping structure within an existing dictionary.

Can you concatenate a dictionary?

Using the merge operator, we can combine dictionaries in a single line of code. We can also merge the dictionaries in-place by using the update operator (|=).

Can you add items to a dictionary in Python?

There is no add() , append() , or insert() method you can use to add an item to a dictionary in Python. Instead, you add an item to a dictionary by inserting a new index key into the dictionary, then assigning it a particular value.


You can define += operator for Dictionary, e.g.,

func += <K, V> (left: inout [K:V], right: [K:V]) { 
    for (k, v) in right { 
        left[k] = v
    } 
}

In Swift 4, one should use merging(_:uniquingKeysWith:):

Example:

let dictA = ["x" : 1, "y": 2, "z": 3]
let dictB = ["x" : 11, "y": 22, "w": 0]

let resultA = dictA.merging(dictB, uniquingKeysWith: { (first, _) in first })
let resultB = dictA.merging(dictB, uniquingKeysWith: { (_, last) in last })

print(resultA) // ["x": 1, "y": 2, "z": 3, "w": 0]
print(resultB) // ["x": 11, "y": 22, "z": 3, "w": 0]

How about

dict2.forEach { (k,v) in dict1[k] = v }

That adds all of dict2's keys and values into dict1.


Swift 4 provides merging(_:uniquingKeysWith:), so for your case:

let combinedDict = dict1.merging(dict2) { $1 }

The shorthand closure returns $1, therefore dict2's value will be used when there is a conflict with the keys.