Python: dynamically accessing nested dictionary keys?
<p>Is there some simple way to access nested dictionary key when at first you don't know which key you will be accessing?</p>

<p>For example:</p>

<pre><code>dct = {'label': 'A', 'config': {'value': 'val1'}}
</code></pre>

<p>In this dictionary I will need to access either <code>label</code> key or <code>value</code> key inside another dict that is accessible through <code>config</code> key.</p>

<p>It depends on state.</p>

<p>For example if we have variable called <code>label</code>, so if:</p>

<pre><code>label = True
if label:
   key = 'label'
</code></pre>

<p>in this case its kind of easy:</p>

<pre><code>dct[key]
</code></pre>

<p>Now if label is false and I need to access nested dictionary, how can I dynamically specify it so I would not need to use ifs on every iterated item (I mean check everytime if <code>label</code> is used instead of <code>value</code>, because I will know that before starting iteration on dictionary full of <code>dct</code> dictionaries)? </p>

<p>like:</p>

<pre><code>label = False
if label:
   key = 'label'
else:
    key = 'config..?' # it should be something like ['config']['value']
</code></pre>

<p>If you know the key to be traversed, you can try out the following. This would work for any level of nested dicts.  </p>

<pre><code>dct = {'label': 'A', 'config': {'value': 'val1'}}

label = True
key = ('label',)
if not label:
    key = ('config', 'value')

ret = dct
for k in key:
  ret = ret[k]

print ret
</code></pre>

python python-2.7 dictionary