Note that there are some explanatory texts on larger screens.

plurals
  1. POPython safe dict navigation, The Right Way
    primarykey
    data
    text
    <h1>TLDR summary</h1> <p>I wrote a function <code>navigateDict</code> that does a safe navigation on a <code>dict</code>, similar to <code>dict.get()</code> but nested. It replaces code like</p> <pre><code>if 1 in data and 'i' in data[1] and 'a' in data[1]['i']: print data[1]['i']['a'] else: print "Not found" </code></pre> <p>with the roughly equivalent</p> <pre><code>found = navigateDict(data, 1, 'i', 'a') if found is not None: print found else: print "Not found" </code></pre> <ul> <li>Is anything similar to this already part of the standard library?</li> <li>Is there a more idiomatic way to do the same thing? <ul> <li>Any response that requires typing any path component key more than once is probably a non-answer.</li> </ul></li> </ul> <h1>Additional details</h1> <p>The implementation is as follows:</p> <pre><code># 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) </code></pre> <p>See the summary for example usage.</p> <p>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.</p> <p>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?</p> <h1>If hits are expected to dominate misses</h1> <p>brionius correctly points out that catching <code>KeyError</code> will work:</p> <pre><code>try: print data[1]['i']['a'] except KeyError: print "Not found" </code></pre> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload