dict.get_deep()
2QdxY4RzWzUUiLuE at potatochowder.com
2QdxY4RzWzUUiLuE at potatochowder.com
Sun Apr 3 11:44:04 EDT 2022
On 2022-04-03 at 18:01:58 +0300,
Kirill Ratkin via Python-list <python-list at python.org> wrote:
> It seems 'case if' should help with types:
>
> case {"users": [{"address": {"street": street}}]} if isinstance(street,
> str):
reduce(lambda x, y: x[y], ["users", 0, "address", "street"], data)
Unless it's y[x] rather than x[y], and there might be a More Cleverer™
way to do it with getattr or one of its relatives instead of lambda.
> 02.04.2022 23:44, Marco Sulla пишет:
> > A proposal. Very often dict are used as a deeply nested carrier of
> > data, usually decoded from JSON. Sometimes I needed to get some of
> > this data, something like this:
> >
> > data["users"][0]["address"]["street"]
> >
> > What about something like this instead?
> >
> > data.get_deep("users", 0, "address", "street")
> >
> > and also, instead of this
> >
> > try:
> > result = data["users"][0]["address"]["street"]
> > except KeyError, IndexError:
> > result = "second star"
> >
> > write this:
> >
> > data.get_deep("users", 0, "address", "street", default="second star")
More information about the Python-list
mailing list