toolz.get_in is designed for exactly this.

https://toolz.readthedocs.io/en/latest/api.html#toolz.dicttoolz.get_in

The whole library is great!

Alex

On Wed, 1 Jul 2020 at 8:03 am, MRAB <python@mrabarnett.plus.com> wrote:
On 2020-06-30 23:26, Daniel. wrote:
> I just want to make clear that safe navegator is enough to deal with this.
>
> Now that this is clear, the use case is almost always the same. I
> received some json as response and want to extract a nested value.
>
> The way I'm doing this today is overloading an infix operator (I'm using
>  >>) to emulate safe navegator so I do
>
> value = data >> get('foo') >> get(0) >> get('bar')
> if value:
>    do something
>
> This get can be found here
> https://github.com/dhilst/geckones_twitter_bots/blob/e6aefe036d30f84835026054676bd018f3339801/utils.py#L91
>
> I started with array implementation them extended to object too. I
> usually has something like this on all my projects that need to extract
> data from requests, or a function that receives a dotted path, anyway..
>
> dict.get composes so nicely so why we don't have list.get too?
>
> Well, the safe navigator can solve this as it will compose as well as
> any adhoc solution with the advantage of short circuit and also it's
> brevity so ... For my use case, at last, safe navigator (or null
> coalescing) will fit better than any list.get can do.
>
[snip]

I'd probably just write a function for it:

def get(data, default, *indexes):
     try:
         for index in indexes:
             data = data[index]
     except (IndexError, KeyError):
         return default

value = get(data, None, 'foo', 0, 'bar')
if value is not None:
     do something
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-leave@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/A6YJUYPK4LDCXAP4EDR5MXCCRL6QOBL5/
Code of Conduct: http://python.org/psf/codeofconduct/