Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a List into a Map in Dart

Tags:

list

map

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

like image 419
Nico Avatar asked May 30 '13 08:05

Nico


People also ask

How do I convert a dart list to a map?

We can convert Dart List to Map in another way: forEach() method. var map2 = {}; list. forEach((customer) => map2[customer.name] = customer.

What's the difference between a list and a map in dart Flutter?

List, Set, Queue are iterable while Maps are not. Iterable collections can be changed i.e. their items can be modified, add, remove, can be accessed sequentially. The map doesn't extend iterable.

What is map () in dart?

Dart Map is an object that stores data in the form of a key-value pair. Each value is associated with its key, and it is used to access its corresponding value. Both keys and values can be any type. In Dart Map, each key must be unique, but the same value can occur multiple times.


1 Answers

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] }; 
like image 184
Alexandre Ardhuin Avatar answered Oct 02 '22 15:10

Alexandre Ardhuin