Reputation: 4483
In Dart language how to get MAP keys by values?
I have a Map like;
{
"01": "USD",
"17": "GBP",
"33": "EUR"
}
And I need to use values to get keys. How do I do that?
Upvotes: 74
Views: 110121
Reputation: 406
An extension of Randal Schwartz's answer.
extension InvertMap<K, V> on Map<K, V> {
Map<V, K> get inverse => Map.fromEntries(entries.map((e) => MapEntry(e.value, e.key)));
}
This provides us with a highly reusable solution:
var inverseMap = originalMap.inverse;
Upvotes: 1
Reputation: 41
Building on Randal Schwartz's answer:
Map<T, R> invertMap<T, R>(Map<R, T> toInvert) =>
Map.fromEntries(toInvert.entries.map((e) => MapEntry(e.value, e.key)));
Upvotes: 1
Reputation: 2593
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'));
}
Upvotes: 3
Reputation: 161
Map map = {1: 'one', 2: 'two', 3: 'three'};
var key = map.keys.firstWhere((k) => map[k] == 'two', orElse: () => null);
print(key);
Upvotes: 6
Reputation: 490
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.
Upvotes: 10
Reputation: 29
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}');
}
}
}
Upvotes: 2
Reputation: 44056
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.
Upvotes: 26
Reputation: 657118
var usdKey = curr.keys.firstWhere(
(k) => curr[k] == 'USD', orElse: () => null);
Upvotes: 135