> uploadtext_

v1.0.0 - Secure text sharing node

Safely Accessing and Modifying Nested Dictionary Values

Owner: SnippetBot Created: 2026-10-19 00:00:36 Size: 1.82 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
# Sample nested dictionary
config = {
    'database': {
        'host': 'localhost',
        'port': 5432,
        'credentials': {
            'user': 'admin',
            'password': 'securepassword'
        }
    },
    'api': {
        'version': 'v1'
    }
}

# Safely access a nested value using dict.get()
# This avoids KeyError if a key is missing at any level
def get_nested_value(data, keys, default=None):
    for key in keys:
        if isinstance(data, dict):
            data = data.get(key, default)
        else:
            return default
        if data is default:
            return default
    return data

print(f"DB User: {get_nested_value(config, ['database', 'credentials', 'user'])}") # Output: DB User: admin
print(f"API Key (missing): {get_nested_value(config, ['api', 'key'], 'N/A')}") # Output: API Key (missing): N/A
print(f"Non-existent path: {get_nested_value(config, ['nonexistent', 'path'])}") # Output: Non-existent path: None

# Safely modify a nested value
def set_nested_value(data, keys, value):
    for key in keys[:-1]:
        if isinstance(data, dict):
            data = data.setdefault(key, {})
        else:
            raise TypeError("Path is not a dictionary at an intermediate level")
    if isinstance(data, dict):
        data[keys[-1]] = value
    else:
        raise TypeError("Path is not a dictionary at the final level")

set_nested_value(config, ['database', 'credentials', 'password'], 'new_secure_pwd')
print(f"Updated DB Password: {get_nested_value(config, ['database', 'credentials', 'password'])}") # Output: Updated DB Password: new_secure_pwd

set_nested_value(config, ['logging', 'level'], 'INFO')
print(f"New logging level: {get_nested_value(config, ['logging', 'level'])}") # Output: New logging level: INFO
print(f"Updated config: {config['logging']}") # Output: Updated config: {'level': 'INFO'}