Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create dictionary from array of tuples?

Let’s say I have array of objects that can be identified and I want to create dictionary from it. I can easily get tuples from my array like so:

let tuples = myArray.map { return ($0.id, $0) } 

But I can’t see initializer for dictionary to take array of tuples. Am I missing something? Do I have create extension for dictionary for this functionality (in fact it’s not hard but I thought it would be supplied by default) or there is easier way to do that?



There is code for extension

extension Dictionary {     public init (_ arrayOfTuples : Array<(Key, Value)>)     {         self.init(minimumCapacity: arrayOfTuples.count)          for tuple in arrayOfTuples         {             self[tuple.0] = tuple.1         }     } } 
like image 910
Adamsor Avatar asked Dec 13 '16 14:12

Adamsor


People also ask

How do I add a list of tuples to a dictionary in Python?

Using the append function we just added the values to the dictionary. This is a simple method of conversion from a list or tuple to a dictionary. Here we pass a tuple into the dict() method which converts the tuple into the corresponding dictionary.

How do you add tuples to a dictionary?

When it is required to add a dictionary to a tuple, the 'list' method, the 'append', and the 'tuple' method can be used. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). The 'append' method adds elements to the end of the list.

Can we use tuple as key in dictionary Python?

Only immutable elements can be used as dictionary keys, and hence only tuples and not lists can be used as keys.


1 Answers

Swift 4

If your tuples is (Hashable, String) you can use:

let array = [("key1", "value1"), ("key2", "value2"), ("key3", "value3")] let dictionary = array.reduce(into: [:]) { $0[$1.0] = $1.1 } print(dictionary) // ["key1": "value1", "key2": "value2", "key3": "value3"] 
like image 175
Sergey Di Avatar answered Sep 22 '22 21:09

Sergey Di