How to get Map keys by values in Dart?

前端 未结 6 1523
小蘑菇
小蘑菇 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:26

    If someone still need a solution, I wrote a simple library to deeply (search inside nested maps either) search by value inside Map. Usage is simple, because deepSearchByValue() is an extension method, so all you need to do is to import my library and call the method on your map:

    import 'package:deep_collection/deep_collection.dart';
    
    
    void main() {
      print({
        "01": "USD",
        "17": "GBP",
        "33": "EUR",
      }.deepSearchByValue((value) => value == 'USD'));
    }
    
    
    0 讨论(0)
  • 2021-02-05 01:26

    You can do the following :

    var mapper = { 
                  '01' : 'USD',
                   '17' : 'GBP'     } 
    
    for(var val in mapper.keys){
    
      switch(mapper[val]){
    
            case 'USD' : {
                                 print('key for ${mapper[val]} is : ' '${val}');  
                }
    
              break;
    
            case 'GBP' : {
                                 print('key for ${mapper[val]} is : ' '${val}');   
                   } 
    
            }
              }
    
    0 讨论(0)
  • 2021-02-05 01:29

    There is another one method (similar to Günter Zöchbauer answer):

    void main() {
    
      Map currencies = {
         "01": "USD",
         "17": "GBP",
         "33": "EUR"
      };
    
      MapEntry entry = currencies.entries.firstWhere((element) => element.value=='GBP', orElse: () => null);
    
      if(entry != null){
        print('key = ${entry.key}');
        print('value = ${entry.value}');
      }
    
    }
    

    In this code, you get MapEntry, which contains key and value, instead only key in a separate variable. It can be useful in some code.

    0 讨论(0)
  • 2021-02-05 01:35
    Map map = {1: 'one', 2: 'two', 3: 'three'};
    
    var key = map.keys.firstWhere((k) => map[k] == 'two', orElse: () => null);
    print(key);
    
    0 讨论(0)
  • 2021-02-05 01:39
    var usdKey = curr.keys.firstWhere(
        (k) => curr[k] == 'USD', orElse: () => null);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题