【问题标题】:How to get/filter values in python3 json list dictionary response?如何在 python3 json 列表字典响应中获取/过滤值?
【发布时间】:2018-07-03 09:26:45
【问题描述】:

以下是我从 API 查询得到的结果。

[{'type':'book','title': 'example1', 'id': 12456, 'price': '8.20', 'qty': '12', 'status': 'available'},
 {'type':'book','title': 'example2', 'id': 12457, 'price': '10.50', 'qty': '5', 'status': 'none'}]

如何在代码中指定仅获取 titlepricestatus 的值对?

所以结果会是这样的:

[{'title': 'example1', 'price': '8.20', 'status': 'available'},
 {'title': 'example2', 'price': '10.50', 'status': 'none'}]

【问题讨论】:

    标签: python json python-3.x list dictionary


    【解决方案1】:

    您可以在列表推导中使用字典推导:

    L = [{'type':'book','title': 'example1', 'id': 12456, 'price': '8.20', 'qty': '12', 'status': 'available'},
         {'type':'book','title': 'example2', 'id': 12457, 'price': '10.50', 'qty': '5', 'status': 'none'}]
    
    keys = ['title', 'price', 'status']
    res = [{k: d[k] for k in keys} for d in L]
    
    print(res)
    
    [{'price': '8.20', 'status': 'available', 'title': 'example1'},
     {'price': '10.50', 'status': 'none', 'title': 'example2'}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多