How to convert a List into a Map in Dart

I looking for an on-the-shelf way to convert a List into a Map in Dart.

In python for example you can do:

l= [ ('a',(1,2)), ('b',(2,3)), ('c',(3,4) ) ]
d=dict(l)
==> {'a': (1, 2), 'c': (3, 4), 'b': (2, 3)}

The dict function expects a List of couple. For each couple, the first element is used as the key and the second as the data.

In Dart I saw the following method for a List : asMap(), but it's not doing what i expect: it use the list index as key. My questions:

  • Do you known anything in Dart libraries to do this ?
  • If not, any plan to add such a feature in the core lib ?

Proposal:

List.toMap() //same as python dict.
List.toMap( (value) => [ value[0], value[1] ] ) //Using anonymous function to return a key and a value from a list item.

Thanks and Regards,

Nicolas


You can use Map.fromIterable:

var result = Map.fromIterable(l, key: (v) => v[0], value: (v) => v[1]);

or collection-for (starting from Dart 2.3):

var result = { for (var v in l) v[0]: v[1] };

In Dart 1.1, you can use this constructor of Map:

new Map.fromIterable(list, key: (v) => v[0], value: (v) => v[1]);

This would be closest to your original proposal.