How to filter a nested dictionary (pythonic way) for a specific value using map or filter instead of list comprehensions?

后端 未结 2 779
不思量自难忘°
不思量自难忘° 2020-12-10 06:42

I\'ve a nested dictionary.

>>> foo = {\'m\': {\'a\': 10}, \'n\': {\'a\': 20}}
>>> 

I\'d like to filter specific values, b

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 07:24

    A list comprehension can do this beautifully.

    >>> foo = {'m': {'a': 10}, 'n': {'a': 20}}
    >>> [v for v in foo.values() if 10 in v.values()]
    [{'a': 10}]
    

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

    In [15]: if 10 in foo['m'].values():
        ...:     result = [foo['m']]
        ...:     
    
    In [16]: result
    Out[16]: [{'a': 10}]
    

提交回复
热议问题