I've a nested dictionary.
>>> foo = {'m': {'a': 10}, 'n': {'a': 20}}
>>>
I'd like to filter specific values, based on the values of 'a'.
I can use list comprehensions for the purpose.
>>> [foo[n] for n in foo if foo[n]['a'] == 10]
[{'a': 10}]
>>>
Using list alone gives me the elements from foo (and not the values of the elements) - as expected:
>>> list(filter(lambda x: foo[x] if foo[x]['a']==10 else None,foo))
['m']
>>>
Using map returns me unwanted 'None' values:
>>> list(map(lambda x: foo[x] if foo[x]['a']==10 else None,foo))
[{'a': 10}, None]
>>>
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.
>>> list(map(lambda t: foo[t], filter(lambda x: foo[x] if foo[x]['a']==10 else None,foo)))
[{'a': 10}]
>>>
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:
>>> list(filter(lambda x: x if x['a'] == 10 else None, foo.values()))
[{'a': 10}]
>>>
I'd like to know if:
- What's the pythonic/recommended approach for this scenario?
- If the last example using filter on dictionary values is an acceptable?
Regards
Sharad
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…