Config File Reader - Problem

You need to build a robust config file reader that can handle various error conditions gracefully.

Your task: Read key=value pairs from a config file and return a dictionary/map. The function should handle:

  • Missing file: Return empty dictionary
  • Malformed lines: Skip lines that don't follow key=value format
  • Missing keys: Skip empty keys or values
  • Whitespace: Trim spaces around keys and values

Input: A string representing the file path

Output: A dictionary/map of successfully parsed key-value pairs

Note: For this problem, file content is simulated - the filepath parameter contains the actual file content as a string with newlines.

Input & Output

Example 1 — Basic Config File
$ Input: filepath = "host=localhost\nport=8080\ndebug=true"
Output: {"host":"localhost","port":"8080","debug":"true"}
💡 Note: Successfully parses three valid key=value pairs from the config content
Example 2 — With Malformed Lines
$ Input: filepath = "host=localhost\ninvalid line\nport=8080\n=empty_key\ndebug=true"
Output: {"host":"localhost","port":"8080","debug":"true"}
💡 Note: Skips 'invalid line' (no =) and '=empty_key' (empty key), keeps only valid entries
Example 3 — Empty File
$ Input: filepath = ""
Output: {}
💡 Note: Empty file content returns empty dictionary

Constraints

  • File content length ≤ 104 characters
  • Maximum 100 key-value pairs
  • Key and value lengths ≤ 256 characters each

Visualization

Tap to expand
📄 Raw Input🔍 Validation✅ Clean OutputConfig File Contenthost=localhost port = 8080 invalid_line(empty line)=missing_keydebug=truename = MyAppkey_no_value=1Check for '=' character2Trim whitespace3Validate key & value4Skip if invalid✗ No '=' → Skip✗ Empty line → Skip✗ Empty key → Skip✓ Valid → KeepDictionary Result"host": "localhost""port": "8080""debug": "true""name": "MyApp"4 Valid Pairs4 Invalid Entries SkippedKey Insight:Validate each line during parsing rather than trying to fix malformed entries - skip gracefully and continue processing.TutorialsPoint - Config File Reader | Robust Error-Handling Parser
Asked in
Google 25 Amazon 30 Microsoft 20 Meta 15
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen