What is the equivalent of this python dictionary in Dart?
16,503
Solution 1
You could use package:collection
's EqualityMap
to define a custom hash algorithim that uses ListEquality
. For example, you could do this:
var map = new EqualityMap.from(const ListEquality(), {
[1, 'a']: 2,
[2, 'a']: 2,
});
assert(map[[1, 'a']] == map[[1, 'a']])
This will be a heavier weight implementation of Map, though.
Solution 2
You have differents way to do this
1. Using a List
var edges = <List, num>{
[1, 'a']: 2,
[2, 'a']: 2,
[2, '1']: 3,
[3, '1']: 3
};
Simple to write, but you won't be able to retrieve data with
edges[[2, 'a']]; // null
Except if you use const
var edges = const <List, num>{
const [1, 'a']: 2,
const [2, 'a']: 2,
const [2, '1']: 3,
const [3, '1']: 3
};
edges[const [2, 'a']]; // 2
2. Using Tuple package
https://pub.dartlang.org/packages/tuple
var edges = <Tuple2<num, String>, num>{
new Tuple2(1, 'a'): 2,
new Tuple2(2, 'a'): 2,
new Tuple2(2, '1'): 3,
new Tuple2(3, '1'): 3
}
edges[new Tuple2(2, 'a')]; // 2
Related videos on Youtube
Author by
Ramses Aldama
Updated on September 15, 2022Comments
-
Ramses Aldama about 1 year
What is the equivalent of this python dictionary in Dart?
edges = {(1, 'a') : 2, (2, 'a') : 2, (2, '1') : 3, (3, '1') : 3}
-
Ramses Aldama over 6 yearsThanks for your answer. Could you explain why you are able to retrieve the data when you use const?
-
Hadrien Lejard over 6 yearshum, actually that is a good question, you could find an answer on gitter by directly asking to the Dart team or people with more experience than me gitter.im/dart-lang/TALK-general
-
Randal Schwartz over 6 yearsbecause
[1, 'a']
does not "=="[1, 'a']
- they are different objects, but const makes them the same object. -
Ramses Aldama over 6 yearsEveryone gave good points but your solution was the only one I could make it work completely in my program.