Checking for Keys and Values
Part of the Logic & Flow section of Coddy's Dart journey — lesson 27 of 65.
Before accessing data in a Map, it's essential to verify that the key or value you're looking for actually exists. Dart provides two methods for this: containsKey() and containsValue().
The containsKey() method checks if a specific key exists in the map, returning true if found and false otherwise. This is particularly useful before trying to access a value, helping you avoid potential errors.
Map<String, String> userPermissions = {
'user123': 'admin',
'user456': 'editor',
'user789': 'viewer'
};
bool hasUser = userPermissions.containsKey('user123');
print(hasUser); // true
bool hasUnknownUser = userPermissions.containsKey('user999');
print(hasUnknownUser); // falseSimilarly, containsValue() checks if a specific value exists anywhere in the map. This method searches through all the values and returns true if it finds a match.
bool hasAdmin = userPermissions.containsValue('admin');
print(hasAdmin); // trueThese methods are crucial for writing safe code that handles missing data gracefully, preventing runtime errors when working with dynamic map contents.
Challenge
EasyCreate a program that manages a user authentication system by verifying user credentials and checking permission levels. Your program should:
- Read a string input representing the system name
- Read multiple pairs of inputs representing usernames and their permission levels (the input will end when you receive
"users_done") - Read a string input representing the username to check
- Read a string input representing the permission level to verify
- Create a Map to store usernames as keys and their permission levels as values
- Use
containsKey()to check if the username exists in the system - Use
containsValue()to check if the specified permission level exists anywhere in the system - Print the authentication analysis in the exact format shown below
For example, if the system name is "Corporate Network", the users include "alice" with "admin", "bob" with "editor", "charlie" with "viewer", "diana" with "admin", the username to check is "alice", and the permission level to verify is "admin", your program should output:
System: Corporate Network
User Database: {alice: admin, bob: editor, charlie: viewer, diana: admin}
Authentication Check:
Username 'alice' exists: true
Permission 'admin' exists in system: true
User 'alice' has permission 'admin': true
Access Status: GRANTED - User authenticated with valid permissions
Security Level: High (admin access detected)If the system name is "School Portal", the users include "teacher1" with "instructor", "student1" with "student", "admin1" with "administrator", the username to check is "guest", and the permission level to verify is "student", your program should output:
System: School Portal
User Database: {teacher1: instructor, student1: student, admin1: administrator}
Authentication Check:
Username 'guest' exists: false
Permission 'student' exists in system: true
User 'guest' has permission 'student': false
Access Status: DENIED - Username not found in system
Security Level: Low (user not registered)If the system name is "Library System", the users include "librarian" with "staff", "member1" with "member", "member2" with "member", the username to check is "librarian", and the permission level to verify is "premium", your program should output:
System: Library System
User Database: {librarian: staff, member1: member, member2: member}
Authentication Check:
Username 'librarian' exists: true
Permission 'premium' exists in system: false
User 'librarian' has permission 'premium': false
Access Status: DENIED - Permission level not available
Security Level: Medium (valid user, invalid permission)Your program must use containsKey() to verify if the username exists and containsValue() to check if the permission level exists anywhere in the system. To check if the specific user has the specific permission, compare the user's actual permission level with the requested one. Determine the security level based on the results: "High" if access is granted with admin-type permissions (admin, administrator, staff), "Medium" if the user exists but has wrong permissions, and "Low" if the user doesn't exist. The input format will be: system name, then alternating usernames and permission levels, ending with "users_done", followed by the username to check and the permission level to verify.
Cheat sheet
Use containsKey() to check if a specific key exists in a Map:
Map<String, String> userPermissions = {
'user123': 'admin',
'user456': 'editor',
'user789': 'viewer'
};
bool hasUser = userPermissions.containsKey('user123');
print(hasUser); // trueUse containsValue() to check if a specific value exists anywhere in a Map:
bool hasAdmin = userPermissions.containsValue('admin');
print(hasAdmin); // trueBoth methods return true if found and false otherwise, helping prevent runtime errors when working with dynamic map contents.
Try it yourself
import 'dart:io';
void main() {
// Read system name
String? systemName = stdin.readLineSync();
// Create a Map to store usernames and their permission levels
Map<String, String> userDatabase = {};
// Read user data until "users_done"
while (true) {
String? input = stdin.readLineSync();
if (input == "users_done") {
break;
}
String username = input!;
String? permission = stdin.readLineSync();
userDatabase[username] = permission!;
}
// Read username to check and permission level to verify
String? usernameToCheck = stdin.readLineSync();
String? permissionToVerify = stdin.readLineSync();
// TODO: Write your code below
// Use containsKey() to check if username exists
// Use containsValue() to check if permission level exists in system
// Check if the specific user has the specific permission
// Determine access status and security level:
// - "High (admin access detected)" if access granted AND permission is admin, administrator, or staff
// - "Medium (standard access)" if access granted but permission is not admin-type
// - "Medium (valid user, invalid permission)" if user exists but has wrong permission
// - "Low (user not registered)" if user does not exist
// Print the authentication analysis
print("System: $systemName");
print("User Database: $userDatabase");
print("Authentication Check:");
// 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