dictionary from tuple sequence?

I have a sequence of (key, value) tuples that exactly match my dictionary form. Surely I didn't need to write this extension myself. Or did I?


extension Dictionary {

public init<Sequence : SequenceType where Sequence.Generator.Element == (Key, Value) >(_ tuples: Sequence) {

self.init()

for (key, value) in tuples {

self[key] = value

}

}

}


I would be happy to know that initializing a dictionary from a tuple sequence already exists, but I was too dumb to figure out how to access it standardly.

Match how? Dictionaries don't contain tuples, and dictionary contents aren't sequential.

Coming from a Python world, it's extremely common to think of generating a dictionary from a sequence of two-element tuples, where each tuple is regarded as a key value pair. So I basically want to hand over a generator or other source of data that emits pairs, and turn those into a dictionary.


For example, given the list

[ ("alpha" : 100), ("beta" : 200) ]

I want back the dictionary I would have gotten via

d["alpha"] = 100

d["beta"] = 200


where d was initially empty. Thinking of dictionaries this way is very intuitive and leads to nice code in all sorts of applications/situations.

Given that Array has:


mutating func appendContentsOf<S : SequenceType where S.Generator.Element == Element>(_ newElements: S)


then it seems like the consistent way to do it in the Swift world would be:


mutating func appendContentsOf<S : SequenceType where S.Generator.Element == (Key, Value)>(_ newElements: S)


instead of making it an initializer. Since the implementation can be written in one line, I'm not sure you've got good cause for complaint that this doesn't exist, but I think you've got good cause for asking that it be added to the standard lib. The APIs for Swift Dictionary looks a bit thin, compared to APIs for Array.

dictionary from tuple sequence?
 
 
Q