Load, Update, Save Settings

Medium ⏱ 12 min 54% acceptance ★★★★☆ 4.3
Write update_setting(path, key, value) that reads a JSON file into a dict (treating a missing file as {}), sets key = value, and writes it back pretty-printed. The read-modify-write cycle every app's settings module performs.

Examples

Example 1
Input
update_setting('cfg.json', 'theme', 'dark')
Output
cfg.json now contains {"theme": "dark"} plus prior keys
Explanation

Existing settings survive; one key changed.

Constraints

  • Missing file starts as empty dict.
  • Write with indent=2.

Topics

JSONfile round-trip

Companies

MicrosoftJetBrainsZoho

Hints

Hint 1

try/except FileNotFoundError around the read.

Hint 2

json.load / json.dump with file objects.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.