Note that there are some explanatory texts on larger screens.

plurals
  1. POPython: Easily access deeply nested dict (get and set)
    primarykey
    data
    text
    <p>I'm building some Python code to read and manipulate deeply nested dicts (ultimately for interacting with JSON services, however it would be great to have for other purposes) I'm looking for a way to easily read/set/update values deep within the dict, without needing a lot of code. </p> <p>@see also <a href="https://stackoverflow.com/questions/3031219/python-recursively-access-dict-via-attributes-as-well-as-index-access">Python: Recursively access dict via attributes as well as index access?</a> -- Curt Hagenlocher's "DotDictify" solution is pretty eloquent. I also like what Ben Alman presents for JavaScript in <a href="http://benalman.com/projects/jquery-getobject-plugin/" rel="nofollow noreferrer">http://benalman.com/projects/jquery-getobject-plugin/</a> It would be great to somehow combine the two.</p> <p>Building off of Curt Hagenlocher and Ben Alman's examples, it would be great in Python to have a capability like:</p> <pre><code>&gt;&gt;&gt; my_obj = DotDictify() &gt;&gt;&gt; my_obj.a.b.c = {'d':1, 'e':2} &gt;&gt;&gt; print my_obj {'a': {'b': {'c': {'d': 1, 'e': 2}}}} &gt;&gt;&gt; print my_obj.a.b.c.d 1 &gt;&gt;&gt; print my_obj.a.b.c.x None &gt;&gt;&gt; print my_obj.a.b.c.d.x None &gt;&gt;&gt; print my_obj.a.b.c.d.x.y.z None </code></pre> <p>Any idea if this is possible, and if so, how to go about modifying the DotDictify solution?</p> <p>Alternatively, the get method could be made to accept a dot notation (and a complementary set method added) however the object notation sure is cleaner.</p> <pre><code>&gt;&gt;&gt; my_obj = DotDictify() &gt;&gt;&gt; my_obj.set('a.b.c', {'d':1, 'e':2}) &gt;&gt;&gt; print my_obj {'a': {'b': {'c': {'d': 1, 'e': 2}}}} &gt;&gt;&gt; print my_obj.get('a.b.c.d') 1 &gt;&gt;&gt; print my_obj.get('a.b.c.x') None &gt;&gt;&gt; print my_obj.get('a.b.c.d.x') None &gt;&gt;&gt; print my_obj.get('a.b.c.d.x.y.z') None </code></pre> <p>This type of interaction would be great to have for dealing with deeply nested dicts. Does anybody know another strategy (or sample code snippet/library) to try?</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.
 

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