Skip to content

Deep get functionality for dictionaries #136776

@omerpresler

Description

@omerpresler

Feature or enhancement

Proposal:

Right now, if I have a nested dictionary (Common occurrence when dealing with a JSON file), and I want to safely reach a value inside a nested dict, I have 2 ways (maybe more technically, but these are the two main ways)

try:
    name = data["user"]["name"]
except KeyError as e:
    name =  "default_value"

Or

data.get("user", {}).get("name", "default_value")

I would like to propose a new method called deepget.
the method will be called like here:

name = data.deepget(["user", "name"],  "default_value")

Or

name = data.deepget("user", "name",  default="default_value")

I would also like your opinion on which way looks better

P.S. - I would like to implement it myself :)

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

https://stackoverflow.com/questions/25833613/safe-method-to-get-value-of-nested-dictionary

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions