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

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy