In Dart language how to get MAP keys by values?
I have a Map like;
{
\"01\": \"USD\",
\"17\": \"GBP\",
\"33\": \"EUR\"
}
And I n
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'));
}
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}');
}
}
}
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.
Map map = {1: 'one', 2: 'two', 3: 'three'};
var key = map.keys.firstWhere((k) => map[k] == 'two', orElse: () => null);
print(key);
var usdKey = curr.keys.firstWhere(
(k) => curr[k] == 'USD', orElse: () => null);
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.