【问题标题】:Python: How to filter a list of dictionaries to get all the values of one keyPython:如何过滤字典列表以获取一个键的所有值
【发布时间】:2017-06-26 10:41:30
【问题描述】:

我有一个python字典列表:

thedata = [{'date': '2002-02', 'data': 2.0}, 
           {'date': '2002-03', 'data': 2.0017}...]

如何仅列出“数据”值?:

[2.0, 2.0017...]

我试过了:

justFigures = list(filter(lambda x: x["data"], thedata))

【问题讨论】:

    标签: python list filter


    【解决方案1】:

    你可以这样试试:

    thedata = [{'date': '2002-02', 'data': 2.0}, 
               {'date': '2002-03', 'data': 2.0017}]
    
    print([a['data'] for a in thedata])
    

    输出:

    [2.0, 2.0017]
    

    【讨论】:

      【解决方案2】:

      我会使用list comprehension

      In [1]: thedata = [{'date': '2002-02', 'data': 2.0},
                         {'date': '2002-03', 'data': 2.0017}]
      
      In [2]: just_figures = [ d['data'] for d in thedata ]
      
      In [3]: just_figures
      Out[3]: [2.0, 2.0017]
      

      【讨论】:

        【解决方案3】:
        thedata = [{'date': '2002-02', 'data': 2.0}, 
                   {'date': '2002-03', 'data': 2.0017}]
        
        # back to your own way, lambda
        # py 2
        print map(lambda a : a["data"], thedata)
        
        # py 3
        print (list(map(lambda a : a["data"], thedata)))
        
        >>> [2.0, 2.0017]
        

        【讨论】:

          猜你喜欢
          • 2013-03-28
          • 1970-01-01
          • 1970-01-01
          • 2022-08-08
          • 2015-05-17
          • 1970-01-01
          • 2012-05-21
          • 1970-01-01
          • 2018-04-30
          相关资源
          最近更新 更多