A better way to access Python dictionaries

Most people, especially novices such as myself, access Python dictionaries like the example below.

device = {
    'hostname' : 'router1',
    'username' : 'admin',
    'password' : 'password',
}

x = device['hostname']

print(x)

This works fine and will return ‘router1’. The issue that arises is when you attempt to access a key that does not exist. Python will return a key error and stop executing code.

device = {
    'hostname' : 'router1',
    'username' : 'admin',
    'password' : 'password',
}

x = device.get('port')

print(x)

In this example we are trying to access the key ‘port’ which doesn’t exist. In the first example this would result in a key error. In this example it will return a value of ‘None’. Optionally a default value can be set for the return.

device = {
    'hostname' : 'router1',
    'username' : 'admin',
    'password' : 'password',
}

x = device.get('port','No Key')

print(x)

This will return ‘No Key’

Leave a comment