Menu
Coddy logo textTech

Key-Value Pairs

Part of the Fundamentals section of Coddy's Dart journey — lesson 59 of 94.

To add or update key-value pairs in a map, use square bracket notation with the key on the left side of the assignment operator.

Create a map of student scores:

Map<String, int> scores = {
  'Alice': 95,
  'Bob': 85
};
print(scores);

After executing the above code, the output will be:

{Alice: 95, Bob: 85}

Add a new key-value pair:

scores['Charlie'] = 90;
print(scores);

After executing the above code, the output will be:

{Alice: 95, Bob: 85, Charlie: 90}

Update an existing value:

scores['Bob'] = 88;
print(scores);

After executing the above code, the output will be:

{Alice: 95, Bob: 88, Charlie: 90}
challenge icon

Challenge

Beginner

In this challenge, you'll practice adding and updating key-value pairs in a Map. You have a studentScores map that already contains some student names and their scores.

Your task is to:

  1. Add a new student named 'David' with a score of 82 to the map
  2. Update Alice's score to 97

After making these changes, the program will print the updated map.

Expected output:

{Alice: 97, Bob: 85, Charlie: 90, David: 82}

Cheat sheet

To add or update key-value pairs in a map, use square bracket notation with the key on the left side of the assignment operator.

Add a new key-value pair:

scores['Charlie'] = 90;

Update an existing value:

scores['Bob'] = 88;

Try it yourself

void main() {
  // Map of student names and their scores
  Map<String, int> studentScores = {
    'Alice': 95,
    'Bob': 85,
    'Charlie': 90
  };
  
  // TODO: Add a new student 'David' with a score of 82
  
  // TODO: Update Alice's score to 97
  
  // Print the updated map
  print(studentScores);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals