Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Depending on what you need, the easiest option may be to use tuples as dictionary keys instead of nested dictionaries:</p> <pre><code>kidshair['allkids', 'child3', 'hair'] mypath = ('allkids', 'child3', 'hair') kidshair[mypath] </code></pre> <p>The only issue with this is that you can't get a portion of the dictionary, so, for example, you can't (easily/efficiently) access everything to do with <code>'child3'</code>. This may or may not be an appropriate solution for you depending on your usage.</p> <p>An alternative with your current structure is to do something like this:</p> <pre><code>&gt;&gt;&gt; from functools import partial &gt;&gt;&gt; test = {"a": {"b": {"c": 1}}} &gt;&gt;&gt; def itemsetter(item): ... def f(name, value): ... item[name] = value ... return f ... &gt;&gt;&gt; mypath = partial(itemsetter(test["a"]["b"]), "c") &gt;&gt;&gt; mypath(2) &gt;&gt;&gt; test {'a': {'b': {'c': 2}}} </code></pre> <p>Here we make a function <code>itemsetter()</code>, which (in the vein of <a href="http://docs.python.org/library/operator.html#operator.itemgetter" rel="nofollow"><code>operator.itemgetter()</code></a>) gives us a function that that sets the relevant key in the given dictionary. We then use <a href="http://docs.python.org/library/functools.html#functools.partial" rel="nofollow"><code>functools.partial</code></a> to generate a version of this function with the key we want pre-filled. It's not quite <code>mypath = blue</code> either, but it's not bad.</p> <p>If you don't want to bother with making something consistent to the <code>operator</code> module, you could simply do:</p> <pre><code>def dictsetter(item, name): def f(value): item[name] = value return f mypath = dictsetter(test["a"]["b"], "c") mypath(2) </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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