Hi all,
In Python, a dictionary can be constructed from an iterable collection of tuples:
>>> listOfTuples = zip(range(10), [-x for x in range(10)])
>>> listOfTuples
[(0, 0), (1, -1), (2, -2), (3, -3), (4, -4), (5, -5), (6, -6), (7, -7), (8, -8), (9, -9)]
>>> theDict = dict(listOfTuples)
>>> theDict
{0: 0, 1: -1, 2: -2, 3: -3, 4: -4, 5: -5, 6: -6, 7: -7, 8: -8, 9: -9}
>>>
Is there an equivalent Scala syntax? I see that you can use a varargs type amount of Tuple2s to construct a map, e.g.
scala> val theMap = Map((0,0),(1,-1))
theMap: scala.collection.immutable.Map[Int,Int] = Map((0,0), (1,-1))
scala> theMap(0)
res4: Int = 0
scala> theMap(1)
res5: Int = -1
scala> val tuplePairs = List((0,0),(1,-1))
tuplePairs: List[(Int, Int)] = List((0,0), (1,-1))
scala> val mapFromIterable = Map(tuplePairs)
<console>:6: error: type mismatch;
found : List[(Int, Int)]
required: (?, ?)
val mapFromIterable = Map(tuplePairs)
^
I could loop through and assign each value manually, but it seems like there must be a better way.
scala> var theMap:scala.collection.mutable.Map[Int,Int] = scala.collection.mutable.Map()
theMap: scala.collection.mutable.Map[Int,Int] = Map()
scala> tuplePairs.foreach(x => theMap(x._1) = x._2)
scala> theMap
res13: scala.collection.mutable.Map[Int,Int] = Map((1,-1), (0,0))