Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a Map comprehension with Scala?

With Python, I can do something like

listOfLists = [('a', -1), ('b', 0), ('c', 1)]
my_dict = {foo: bar for foo, bar in listOfLists}

my_dict == {'a': -1, 'b': 0, 'c': 1} => True

I know this as a dictionary comprehension. When I look for this operation with Scala, I find this incomprehensible document (pun intended).

Is there an idiomatic way to do this with Scala?

Bonus question: Can I filter with this operation as well like my_dict = {foo: bar for foo, bar in listOfLists if bar > 0}?

like image 619
munk Avatar asked Jan 30 '26 21:01

munk


1 Answers

First, let's parse your Python code to figure out what it's doing.

my_dict = {
  foo: bar       <-- Key, value names
  for foo, bar   <-- Destructuring a list
  in listOfLists <-- This is where they came from
}

So you can see that even in this very short example there's actually considerable redundancy and plenty of potential for failure if listOfLists isn't actually what it says it is.

If listOfLists actually is a list of pairs (key, value), then in Scala it's trivial:

listOfPairs.toMap

If, on the other hand, it really is lists, and you want to pull off the first one to make the key and save the rest as a value, it would be something like

listOfLists.map(x => x.head -> x.tail).toMap

You can select some of them by using collect instead. For instance, maybe you only want the lists of length 2 (you could if x.head > 0 to get your example), in which case you

listOfLists.collect{
  case x if x.length == 2 => x.head -> x.last
}.toMap

or if it is literally a List, you could also

listOfLists.collect{
  case key :: value :: Nil => key -> value
}.toMap
like image 192
Rex Kerr Avatar answered Feb 02 '26 13:02

Rex Kerr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!