2

Javascript has a useful pattern called optional chaining, that lets you safely traverse through a deeply nested object without key errors.

For example:

const foo= {
    correct: {
        key: 'nested'
    }
}
const correct =    foo?.correct?.key
const incorrect =  foo?.incorrect?.key

You can also do it the old fashioned way like this:

const nested = foo && foo.bar && foo.bar.key

Does Python have a pattern as clean as this for traversing nested dictionaries? I find it particularly verbose when traversing deeply nested objects with long key names.

This is the closest I can get in Python:

getattr(getattr(foo, 'correct', None), 'key', None)

Which is pretty gross and starts getting dumb beyond two or three nestings

Ucinorn
  • 648
  • 7
  • 21
  • You could use a `collections.DefaultDict` instead of the built-in `dict` to get some behavior like this, I suspect. – Him Apr 18 '23 at 02:47
  • `.get()` with a default value of an empty dict might be a bit better? `foo.get('correct', {}).get('key')` – John Gordon Apr 18 '23 at 02:57

0 Answers0