Map Properties: keys & values
Part of the Logic & Flow section of Coddy's Dart journey — lesson 28 of 65.
When working with Map collections, you sometimes need to extract all the keys or all the values separately. Dart provides two convenient properties for this: .keys and .values.
The .keys property returns an iterable containing all the keys from the map, while .values returns an iterable containing all the corresponding values. These properties are particularly useful when you need to process keys and values independently.
Map<String, double> inventory = {
'Laptop': 999.99,
'Mouse': 25.50,
'Keyboard': 75.00
};
Iterable<String> productNames = inventory.keys;
Iterable<double> prices = inventory.values;
print(productNames); // (Laptop, Mouse, Keyboard)
print(prices); // (999.99, 25.5, 75.0)Since these properties return iterables rather than lists, you can convert them to lists using .toList() if you need list-specific functionality. This separation of keys and values is especially helpful when you need to analyze or manipulate one aspect of your data independently from the other.
Challenge
EasyCreate a program that manages a digital library system by analyzing book collections and extracting information about titles and their publication years. Your program should:
- Read a string input representing the library name
- Read multiple pairs of inputs representing book titles and their publication years (the input will end when you receive
"catalog_done") - Create a Map to store each book title as the key and its publication year as the value
- Use the
.keysproperty to extract all book titles and convert them to a List - Use the
.valuesproperty to extract all publication years and convert them to a List - Find the oldest book by identifying the minimum year from the values
- Find the newest book by identifying the maximum year from the values
- Print the library analysis in the exact format shown below
For example, if the library name is "Central Library" and the catalog includes "To Kill a Mockingbird" with year 1960, "1984" with year 1949, "The Great Gatsby" with year 1925, "Harry Potter" with year 1997, your program should output:
Library: Central Library
Book Collection Analysis:
All book titles: [To Kill a Mockingbird, 1984, The Great Gatsby, Harry Potter]
All publication years: [1960, 1949, 1925, 1997]
Total books in collection: 4
Oldest book year: 1925
Newest book year: 1997
Collection span: 72 years
Status: Library catalog analysis completedIf the library name is "University Library" and the catalog includes "Pride and Prejudice" with year 1813, "Moby Dick" with year 1851, "Brave New World" with year 1932, your program should output:
Library: University Library
Book Collection Analysis:
All book titles: [Pride and Prejudice, Moby Dick, Brave New World]
All publication years: [1813, 1851, 1932]
Total books in collection: 3
Oldest book year: 1813
Newest book year: 1932
Collection span: 119 years
Status: Library catalog analysis completedIf the library name is "Community Library" and the catalog includes "The Hobbit" with year 1937, "Dune" with year 1965, "Neuromancer" with year 1984, "The Martian" with year 2011, "Klara and the Sun" with year 2021, your program should output:
Library: Community Library
Book Collection Analysis:
All book titles: [The Hobbit, Dune, Neuromancer, The Martian, Klara and the Sun]
All publication years: [1937, 1965, 1984, 2011, 2021]
Total books in collection: 5
Oldest book year: 1937
Newest book year: 2021
Collection span: 84 years
Status: Library catalog analysis completedYour program must use the .keys property to extract all book titles and the .values property to extract all publication years. Convert both iterables to Lists using .toList(). Calculate the collection span by subtracting the oldest year from the newest year. The input format will be: library name, then alternating book titles and publication years (as strings that need to be converted to integers), ending with "catalog_done".
Cheat sheet
Use .keys to extract all keys from a Map and .values to extract all values:
Map<String, double> inventory = {
'Laptop': 999.99,
'Mouse': 25.50,
'Keyboard': 75.00
};
Iterable<String> productNames = inventory.keys;
Iterable<double> prices = inventory.values;
print(productNames); // (Laptop, Mouse, Keyboard)
print(prices); // (999.99, 25.5, 75.0)Convert iterables to lists using .toList() for list-specific functionality:
List<String> namesList = inventory.keys.toList();
List<double> pricesList = inventory.values.toList();Try it yourself
import 'dart:io';
void main() {
// Read library name
String? libraryName = stdin.readLineSync();
// Create a Map to store book titles and publication years
Map<String, int> bookCatalog = {};
// Read book titles and years until "catalog_done"
while (true) {
String? input = stdin.readLineSync();
if (input == "catalog_done") {
break;
}
String bookTitle = input!;
String? yearInput = stdin.readLineSync();
int publicationYear = int.parse(yearInput!);
bookCatalog[bookTitle] = publicationYear;
}
// TODO: Write your code below
// Extract book titles using .keys property and convert to List
// Extract publication years using .values property and convert to List
// Find oldest and newest years
// Calculate collection span
// Print the library analysis in the required format
print("Library: $libraryName");
print("Book Collection Analysis:");
// Add your output statements here
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List