Skip to content

Instantly share code, notes, and snippets.

@luandy64
Created November 13, 2023 16:36
Show Gist options
  • Save luandy64/e0ba5d71ab6415190ff572f1c63e8369 to your computer and use it in GitHub Desktop.
Save luandy64/e0ba5d71ab6415190ff572f1c63e8369 to your computer and use it in GitHub Desktop.
Python `.get()` chaining
>>> data = {}
>>> more_key = "paging"
>>> print(data[more_key]["next"]["after"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'paging'
>>>
>>> print(data.get(more_key).get('next').get('after'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'get'
>>>
>>>
>>> data = {"paging": {}}
>>> print(data[more_key]["next"]["after"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'next'
>>> print(data.get(more_key).get('next').get('after'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'get'
>>>
>>>
>>> data = {"paging": {"next": {}}}
>>> print(data[more_key]["next"]["after"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'after'
>>> print(data.get(more_key).get('next').get('after'))
None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment