简体   繁体   English

如何使用 Python 从 List 中提取值?

[英]How extract Values from List with Python?

I requested a JSON File from API.我从 API 请求了一个 JSON 文件。 Then I want to parse/save just some values out of the File.然后我想解析/保存文件中的一些值。

Code:代码:

First the request call:首先是请求调用:

request = requests.get(self.url, verify = False)
request_data = request.json()

Example File (Type <class 'list'>):示例文件(类型 <class 'list'>):

[
    {
        "id1": null,
        "id2": "test1",
        "id3": "test2",
    }
    {
        "id1": null,
        "id2": "test3",
        "id3": "test4",
    }
]

Now I just want to get all id2 and their value, I tried with the code below, but it only works with dictionaries, how can I convert the list to a dictionary?现在我只想获取所有 id2 及其值,我尝试使用下面的代码,但它仅适用于字典,如何将列表转换为字典? Or can I extract the values with a list too?或者我也可以用列表提取值吗?

value = {}
output_data = {}
value["id2"] = data.get("id2")
output_data.append(value)

You can do as below:您可以执行以下操作:

var = [
    {
        "id1": "null",
        "id2": "test1",
        "id3": "test2",
    },
    {
        "id1": "",
        "id2": "test3",
        "id3": "test4",
    }
]
output = []
for i in var:
    output.append(i['id2'])

print(output)

It looks like you have a list of dictionaries.看起来您有一个字典列表。 One Pythonic way of dealing with this would be:处理这个问题的一种 Pythonic 方法是:

all_id2s = [entry['id2'] for entry in request_data]

This would create an array containing just the "id2" elements, like:这将创建一个仅包含"id2"元素的数组,例如:

['test1', 'test3']

Check it out on IDEOne: https://ideone.com/5iVZhw在 IDEOne 上查看: https ://ideone.com/5iVZhw

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM