CodexBloom - Programming Q&A Platform

Handling Nested Dictionary Updates in Python 3.10 with Default Values

πŸ‘€ Views: 52 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
python dictionary nested-dictionaries Python

I'm reviewing some code and I need help solving I'm currently working on a Python 3.10 application where I need to update nested dictionaries. The issue arises when I attempt to set default values for keys that may not exist, and I want this to happen recursively. I'm using a structure that looks like this: ```python config = { 'database': { 'host': 'localhost', 'port': 5432 }, 'api': { 'timeout': 30 } } ``` If I want to update the `timeout` value and ensure that defaults are applied to other keys, I wrote this function: ```python def update_config(config, updates): for key, value in updates.items(): if isinstance(value, dict) and key in config: update_config(config[key], value) else: config[key] = value ``` However, when I call it like this: ```python update_config(config, { 'database': {'port': 5433}, 'api': {'timeout': 45, 'retries': 3} }) ``` I expect to see the `retries` key added to `api` and the `port` updated, but I encounter a situation where the entire `database` section gets replaced instead of just updating the `port`. The output looks like this: ```python { 'database': {'host': 'localhost', 'port': 5433}, 'api': {'timeout': 45} } ``` I want the final configuration to include `retries` with a default of 1 if it’s not provided in the updates. I thought about checking for existing keys before updating, but it seems cumbersome. What’s the best approach to preserve existing keys and provide defaults in nested dictionaries without overwriting them? Any suggestions or improvements to my current implementation would be greatly appreciated! I'm developing on Debian with Python. I'm open to any suggestions. I've been using Python for about a year now. Any help would be greatly appreciated!