skip to Main Content

How can I reverse the key and value of the map?

for example, {1:a , 2:b , 3:c} => {a:1 ,b:2 ,c:3}

2

Answers


  1. You can do this:

    const items = {1:'a' , 2:'b' , 3:'c'};
    
    void main() {
      final inverted = items.map((key, value) => MapEntry(value, key));
      print(inverted);
    }
    

    It logs

    {a: 1, b: 2, c: 3}
    
    Login or Signup to reply.
  2. Try this piece of code:

    Map<int, String> map = {1: "a", 2: "b", 3: "c"};
    
      Iterable<String> values = map.values;
      Iterable<int> keys = map.keys;
      Map<String, int> reversedMap = Map.fromIterables(values, keys);
    
      print(reversedMap); // {a:1 ,b:2 ,c:3}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search