How to filter a nested dictionary (pythonic way) for a specific value using map or filter instead of list comprehensions?
<p>I've a nested dictionary.</p>

<pre><code>&gt;&gt;&gt; foo = {'m': {'a': 10}, 'n': {'a': 20}}
&gt;&gt;&gt; 
</code></pre>

<p>I'd like to filter specific values, based on the values of 'a'.</p>

<p>I can use list comprehensions for the purpose.</p>

<pre><code>&gt;&gt;&gt; [foo[n] for n in foo if foo[n]['a'] == 10]
[{'a': 10}]
&gt;&gt;&gt; 
</code></pre>

<p>Using list alone gives me the elements from foo (and not the values of the elements) - as expected:</p>

<pre><code>&gt;&gt;&gt; list(filter(lambda x: foo[x] if foo[x]['a']==10 else None,foo))
['m']
&gt;&gt;&gt; 
</code></pre>

<p>Using map returns me unwanted 'None' values:</p>

<pre><code>&gt;&gt;&gt; list(map(lambda x: foo[x] if foo[x]['a']==10 else None,foo))
[{'a': 10}, None]
&gt;&gt;&gt; 
</code></pre>

<p>Combining these two, I can fetch the desired value. But I guess foo is iterated twice - once each for filter and map. The list comprehension solution needs me to iterate just once.</p>

<pre><code>&gt;&gt;&gt; list(map(lambda t: foo[t], filter(lambda x: foo[x] if foo[x]['a']==10 else None,foo)))
[{'a': 10}]
&gt;&gt;&gt; 
</code></pre>

<p>Here's another approach using just filter. This gives me the desired values but I'm not sure if iterating over values of a dictionary is a good/pythonic approach:</p>

<pre><code>&gt;&gt;&gt; list(filter(lambda x: x if x['a'] == 10 else None, foo.values()))
[{'a': 10}]
&gt;&gt;&gt; 
</code></pre>

<p>I'd like to know if:</p>

<ol>
<li>What's the pythonic/recommended approach for this scenario?</li>
<li>If the last example using filter on dictionary values is an acceptable?</li>
</ol>

<p>Regards</p>

<p>Sharad</p>

<p>A list comprehension can do this beautifully.</p>

<pre><code>&gt;&gt;&gt; foo = {'m': {'a': 10}, 'n': {'a': 20}}
&gt;&gt;&gt; [v for v in foo.values() if 10 in v.values()]
[{'a': 10}]
</code></pre>

<p>You don't need the for loop or the list comprehension if you are matching against a known key in the dictionary.</p>

<pre><code>In [15]: if 10 in foo['m'].values():
    ...:     result = [foo['m']]
    ...:     

In [16]: result
Out[16]: [{'a': 10}]
</code></pre>

python list dictionary list-comprehension python-3.5