【问题标题】:filter the values of dictionary items in a list by their key in python [duplicate]通过python中的键过滤列表中字典项的值[重复]
【发布时间】:2016-03-03 18:41:48
【问题描述】:

我在 python 中有一个这样的列表:

x = [{'A': 1, 'B': 2}, {'A': 3, 'B': 4}, {'A': 5, 'B': 6}]

它的成员是Dictionary 项目。我想过滤列表以获取此列表:

X = [1, 3, 5]

有没有像x[0:2]['A'] 这样的神奇命令来过滤这样的列表?

【问题讨论】:

  • [D['A'] for D in x]
  • @El'endiaStarman 谢谢。那行得通。你能把它作为答案发布吗?
  • @El'endiaStarman 你可以使用[D.get('A') for D in x] 来避免密钥错误
  • @VigneshKalai:感谢您的提示!我已将其包含在我的答案中。
  • 您是否对列表或字典进行过研究?

标签: python list dictionary


【解决方案1】:

有很多方法可以做到这一点。

  1. operator.itemgetter

    如果你碰巧经常做这个操作,那么更喜欢这种方式

    >>> from operator import itemgetter
    >>> get_a = itemgetter('A')
    >>> [get_a(item) for item in x]
    [1, 3, 5]
    

    map

    >>> list(map(get_a, x))
    [1, 3, 5]
    
  2. 最简单的方法是使用[] 运算符,像这样

    >>> [item['A'] for item in X]
    [1, 3, 5]
    
  3. 如果你想避免在A不存在的字典中出现KeyError,你可以使用dict.get,它默认返回None,像这样

    >>> [item.get('A') for item in X]
    [1, 3, 5]
    

【讨论】:

    【解决方案2】:

    您可以使用列表推导。

    >>> y = [D['A'] for D in x]
    >>> y
    [1, 3, 5]
    

    另外,作为Vignesh Kalai pointed out,如果您希望此代码即使密钥不在字典中也能正常工作,请改用此代码:

    [D.get('A') for D in x]
    

    然后用list(filter(bool,y))取出Nones。像这样:

    >>> x = [{'A': 1, 'B': 2}, {'A': 3, 'B': 4}, {'A': 5, 'B': 6}, {'B': 8}]
    >>> y = [D['A'] for D in x]
    Traceback (most recent call last):
      File "<pyshell#55>", line 1, in <module>
        y = [D['A'] for D in x]
      File "<pyshell#55>", line 1, in <listcomp>
        y = [D['A'] for D in x]
    KeyError: 'A'
    >>> y = [D.get('A') for D in x]
    >>> y
    [1, 3, 5, None]
    >>> y = list(filter(bool,y))
    >>> y
    [1, 3, 5]
    

    【讨论】:

      猜你喜欢
      • 2013-05-22
      • 2020-05-21
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 2020-11-04
      • 2020-09-11
      • 1970-01-01
      相关资源
      最近更新 更多