dict.get_deep()

Dieter Maurer dieter at handshake.de
Sun Apr 3 12:57:50 EDT 2022


Marco Sulla wrote at 2022-4-2 22:44 +0200:
>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")

You know you can easily implement this yourself -- in your own
`dict` subclass.

You can also customize the JSON decoding (--> `object_hook`)
to determine how a JSON object is mapped to a Python object;
it defaults to `dict` but you could use your own `dict` subclass.


More information about the Python-list mailing list