gpt4 book ai didi

python - 如何从 2 个值集的列表中提取 ID 列表

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:12 24 4
gpt4 key购买 nike

所以这段代码的结果是一个像这样的列表:

[
{'id': 'abcd', 'created_time': '2016-12-09T13:45:43+0000'},
{'id': 'efgh', 'created_time': '2016-12-09T07:47:54+0000'},
{'id': 'ijkl', 'created_time': '2016-12-09T07:47:34+0000'},
{'id': 'mnop', 'created_time': '2016-12-09T07:47:09+0000'},
{'id': 'qrst', 'created_time': '2016-12-09T07:46:52+0000'}
]]

我想得到一个像这样的列表:

ID
abcd
efgh
ijkl
mnop
qrst

我很感激任何帮助,因为我正在用这个把我的头发拉出来!

def d_values(d, depth):
if depth == 1:
for i in d.values():
yield i
else:
for v in d.values():
if isinstance(v, dict):
for i in d_values(v, depth-1):
yield i


def Get_Message_IDs (Conversation_ID, Token):

Request = urllib.request.urlopen('https://graph.facebook.com/v2.8/' + Conversation_ID +'?fields=messages&access_token=' + Token)
ids = list()
try:
response = Request
output = response.read()
output = output.decode("utf-8")
output = ast.literal_eval(output)
output = list(d_values(output, 2))
print(output)
except Exception as exec:
print(exec)

最佳答案

假设末尾额外的 ] 是一个拼写错误,您的列表看起来像一个 json 列表。因此,只需使用适当的 json 模块解析它(是的,JSON 语法和 Python 字典和列表非常相似):

import json
# response is the result of your urllib.requests.urlopen(...)
my_list = json.loads(response.read().decode('utf-8'))

# then you can access the ids
print([element['id'] for element in my_list)

# if you want the exact output you mentioned in your question:
print("ID")
for element in my_list:
print(element.get('id'))

顺便说一句,我建议您使用外部 requests 库而不是内置的 urllib,它将免除您解析 JSON 响应的所有痛苦:

import requests
response = requests.get('https://graph.facebook.com/v2.8/' + Conversation_ID +'?fields=messages&access_token=' + Token)
print(response.json())

关于python - 如何从 2 个值集的列表中提取 ID 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41062221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com