Collections
Maps
Insert and Lookup
A map literal {key: value, ...} builds a key-value store. Assigning to a missing key inserts it.
Program
Play the program to insert one entry and read another.
maps.dart
Replay: real traced execution (multi-file project)
void main() {
var scores = {'Ada': 9, 'Lin': 12};
scores['Mia'] = 6;
print(scores['Lin']);
}
scores ← {Ada: 9, Lin: 12}
1void main() {2 var scores = {'Ada': 9, 'Lin': 12};3 scores['Mia'] = 6;values this step{Ada: 9, Lin: 12}scoresscores ← {Ada: 9, Lin: 12, Mia: 6}
2var scores = {'Ada': 9, 'Lin': 12};3scores['Mia'] = 6;4print(scores['Lin']);values this step{Ada: 9, Lin: 12} → {Ada: 9, Lin: 12, Mia: 6}scoresprint(scores['Lin']);
3 scores['Mia'] = 6;4 print(scores['Lin']);5}output12values this step{Ada: 9, Lin: 12, Mia: 6}scores
Insert, Then Lookup
- Start with scores for
AdaandLin. - Assigning
scores['Mia'] = 6inserts a new key. - Looking up
scores['Lin']reads the existing value. - The printed value is
12. | Key | Value after insert | | --- | --- | |Ada|9| |Lin|12| |Mia|6|
map literal
`{'Ada': 9, ...}` is a `Map<String, int>`.
insert
`scores['Mia'] = 6` inserts a new entry.
lookup
`scores['Lin']` reads a value by key.
Exercise: maps.dart
Insert one new score into a map, then look up and print an existing score