How to fill a List with entries from a Map in Dart

Viewed 251

I want to do the equivalent of this Python code in Dart. Possibly as a one liner I could use in a return statement.

m = {1: 'a', 2: 'b', 3: 'c'}
l = [1, 3]
[m[index] for index in l]

this results in a new list like this ['a', 'c']

A long version of this in Dart would be this.

List<String> r = [];
for (var key in l) {
  r.add(m[key]);
}
1 Answers

I think this is what you are asking for:

void main() {
  final m = {1: 'a', 2: 'b', 3: 'c'};
  final l = [1, 3, 4];

  List<String> r1 = m.entries.where((e) => l.contains(e.key)).map((e) => e.value).toList();
  List<String> r2 = l.where((k) => m.containsKey(k)).map((k) => m[k]).toList();
  print(r1); // [a, c]
  print(r2); // [a, c]
}

Update 1: Added another example (r2) which iterate over the list instead.

Update 2: Added check to second solution so it only map keys there are in the map.

Related