Python safe dict navigation, The Right Way

psmay

TLDR summary

I wrote a function navigateDict that does a safe navigation on a dict, similar to dict.get() but nested. It replaces code like

if 1 in data and 'i' in data[1] and 'a' in data[1]['i']:
    print data[1]['i']['a']
else:
    print "Not found"

with the roughly equivalent

found = navigateDict(data, 1, 'i', 'a')
if found is not None:
    print found
else:
    print "Not found"
  • Is anything similar to this already part of the standard library?
  • Is there a more idiomatic way to do the same thing?
    • Any response that requires typing any path component key more than once is probably a non-answer.

Additional details

The implementation is as follows:

# Allow fallback value other than None
def navigateDictEx(d, keys, fallback=None):
    for key in keys:
        if key in d:
            d = d[key]
        else:
            return fallback
    return d

def navigateDict(d, *keys):
    return navigateDictEx(d, keys)

See the summary for example usage.

Pythonic or not, this function reduces repetition in a place where redundancy is a bad idea. For example, changing one path component in the example requires up to three distinct values to be modified as one in the original example, but only one in the modified example. Given my regular tendency to err, this is a big win.

Ultimately I'm asking this: Is there something in the standard library that does this, or am I going to need to find a place for it in my project's library?

If hits are expected to dominate misses

brionius correctly points out that catching KeyError will work:

try:
    print data[1]['i']['a']
except KeyError:
    print "Not found"

This might be the way I go; it's pretty terse and cuts the repetition. However, it does reflect an assumption that there will be more hits than misses. If there's a better way of assuming the opposite I'd like to know that, also.

Brionius

One way to do this is as follows:

try:
    print data[1]['i']['a']
except KeyError:
    print "Not found!"

It's in line with the spirit of duck-typing. It may or may not be as fast, as I believe handling exceptions carries a certain amount of overhead, but it's certainly "safe".

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Python: right justified and ordered dict

From Dev

Python dict get function not doing the right thing?

From Dev

Python efficient way to filter dict

From Dev

Python: Right way to extend list

From Dev

How to import the right way in python?

From Dev

How to implement tab bar controller with navigation controller in right way

From Dev

What is a safe way to "bound" environment variable in python?

From Dev

Best way to aggregate a simple dict in Python

From Dev

Python dict get value fastest way

From Dev

Best way to aggregate a simple dict in Python

From Dev

Best way for dict with duplicate keys in python

From Dev

This is Thread-Safe right?

From Dev

This is Thread-Safe right?

From Dev

Right way to check for key in dictionary in python

From Dev

Python/Django handling HTTP requests in the right way

From Dev

What is the right way to do "loose coupling" in python?

From Dev

What is the right way to manage namespaces in Python 3?

From Dev

What is the right way to print fibonacci sequence in python

From Dev

What is the right way to print fibonacci sequence in python

From Dev

Safe navigation operator (&.) for nil

From Dev

Safe Navigation of indexed objects

From Dev

Safe Navigation Operator with Any()

From Dev

Converting Bottle FORMSDICT to a Python dictionary (in a thread safe way)

From Dev

Simple and safe way to wait for a Python Process to complete when using a Queue

From Dev

Python-Bash: unicode strings break bash; safe way to fix?

From Dev

Are dict thread-safe with pypy?

From Dev

Which is a right safe MySQLi query?

From Dev

proper way to subclass object for __getitem__() in python if emulating a dict

From Dev

Is there any way to use get with object instead of dict in python

Related Related

  1. 1

    Python: right justified and ordered dict

  2. 2

    Python dict get function not doing the right thing?

  3. 3

    Python efficient way to filter dict

  4. 4

    Python: Right way to extend list

  5. 5

    How to import the right way in python?

  6. 6

    How to implement tab bar controller with navigation controller in right way

  7. 7

    What is a safe way to "bound" environment variable in python?

  8. 8

    Best way to aggregate a simple dict in Python

  9. 9

    Python dict get value fastest way

  10. 10

    Best way to aggregate a simple dict in Python

  11. 11

    Best way for dict with duplicate keys in python

  12. 12

    This is Thread-Safe right?

  13. 13

    This is Thread-Safe right?

  14. 14

    Right way to check for key in dictionary in python

  15. 15

    Python/Django handling HTTP requests in the right way

  16. 16

    What is the right way to do "loose coupling" in python?

  17. 17

    What is the right way to manage namespaces in Python 3?

  18. 18

    What is the right way to print fibonacci sequence in python

  19. 19

    What is the right way to print fibonacci sequence in python

  20. 20

    Safe navigation operator (&.) for nil

  21. 21

    Safe Navigation of indexed objects

  22. 22

    Safe Navigation Operator with Any()

  23. 23

    Converting Bottle FORMSDICT to a Python dictionary (in a thread safe way)

  24. 24

    Simple and safe way to wait for a Python Process to complete when using a Queue

  25. 25

    Python-Bash: unicode strings break bash; safe way to fix?

  26. 26

    Are dict thread-safe with pypy?

  27. 27

    Which is a right safe MySQLi query?

  28. 28

    proper way to subclass object for __getitem__() in python if emulating a dict

  29. 29

    Is there any way to use get with object instead of dict in python

HotTag

Archive