How to get Map keys by values in Dart?

前端 未结 6 1522
小蘑菇
小蘑菇 2021-02-05 00:43

In Dart language how to get MAP keys by values?

I have a Map like;

{
  \"01\": \"USD\",
  \"17\": \"GBP\",
  \"33\": \"EUR\"
}

And I n

6条回答
  •  星月不相逢
    2021-02-05 01:40

    If you will be doing this more than a few times on the same data, you should create an inverse map so that you can perform simple key lookup instead of repeated linear searches. Here's an example of reversing a map (there may be easier ways to do this):

    main() {
      var orig = {"01": "USD", "17": "GBP", "33": "EUR"};
      var reversed = Map.fromEntries(orig.entries.map((e) => MapEntry(e.value, e.key)));
      for (var kv in reversed.entries) {
        print(kv);
      }
    }
    

    Edit: yes, reversing a map can simply be:

    var reversed = orig.map((k, v) => MapEntry(v, k));
    

    Tip of the hat to Joe Conway on gitter. Thanks.

提交回复
热议问题