如何使用映射或过滤器而不是列表推导为特定值过滤嵌套字典(Python方式)? [英] How to filter a nested dictionary (pythonic way) for a specific value using map or filter instead of list comprehensions?

查看:109
本文介绍了如何使用映射或过滤器而不是列表推导为特定值过滤嵌套字典(Python方式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的字典.

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

我想根据'a'的值过滤特定的值.

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}]
>>> 

仅使用list即可给我foo中的元素(而不是元素的值)-符合预期:

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]
>>> 

结合这两个,我可以获取所需的值.但是我想foo​​被迭代了两次-一次用于过滤器和映射.列表理解解决方案只需要我重复一次即可.

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}]
>>> 

这是仅使用过滤器的另一种方法.这给了我想要的值,但是我不确定对字典的值进行迭代是否是一种好方法/pythonic方法:

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}]
>>> 

我想知道是否:

  1. 在这种情况下,pythonic/推荐的方法是什么?
  2. 如果最后一个在字典值上使用过滤器的示例是否可以接受?

致谢

Sharad

推荐答案

列表理解可以做到这一点.

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}]

如果您与字典中的已知键匹配,则不需要for循环或列表理解.

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}]

这篇关于如何使用映射或过滤器而不是列表推导为特定值过滤嵌套字典(Python方式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆