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

后端 未结 2 781
不思量自难忘°
不思量自难忘° 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:29

    If you want to return the full nested dictionary if it contains a, a list comprehension is probably the cleanest way. Your initial list comprehension would work:

    [foo[n] for n in foo if foo[n]['a'] == 10]
    

    You can also avoid the lookup on n with:

    [d for d in foo.values() if d['a'] == 10]
    

    List comprehensions are generally considered more Pythonic than map or filter related approaches for simpler problems like this, though map and filter certainly have their place if you're using a pre-defined function.

    This gives me the desired values but I'm not sure if iterating over values of a dictionary is a good/pythonic approach.

    If you want to return all values of a dictionary that meet a certain criteria, I'm not sure how you would be able to get around not iterating over the values of a dictionary.

    For a filter-based approach, I would do it as:

    list(filter(lambda x: x['a'] == 10, foo.values()))
    

    There's no need for the if-else in your original code.

提交回复
热议问题