Dart Map comprehension

3.2k views Asked by At

In python I'd write:

{a:0 for a in range(5)}

to get

{0: 0, 1: 0, 2: 0, 3: 0, 4: 0}

How can I achieve the same in Dart?

So far I have this:

List<Map<String, double>>.generate(5, (i) => { i: 0 });

but this generates list of maps [{0: 0}, {1: 0}, {2: 0}, {3: 0}, {4: 0}],

while I want a simple map

3

There are 3 answers

1
jamesdlin On BEST ANSWER

Dart has a collection for syntax that is similar to Python's comprehensions. The Dart Language Tour provides examples for Lists, but it can be used for Sets and Maps too:

final map = {for (var a = 0; a < 5; a += 1) a: 0};

You can consult the feature specification for more details.

6
CopsOnRoad On
Map<int, int> map = {};
for (int i = 0; i < 5; i++) {
  map[i] = 0;
}

Prints

{0: 0, 1: 0, 2: 0, 3: 0, 4: 0}

Edit:

You can also try this approach:

List<int> list1 = List.generate(5, (i) => i);
List<int> list2 = List.generate(5, (i) => 0);
var map = Map.fromIterables(list1, list2);
0
julemand101 On

You can do it this way if you want a solution using one line:

void main() {
  final map = Map.fromEntries(Iterable.generate(5, (i) => MapEntry(i, 0)));
  print(map); // {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
}