从dict中获取一个列表并从该列表中保存一个元素

2024-09-24 00:35:38 发布

您现在位置:Python中文网/ 问答频道 /正文

标题非常明确。我有一个dict(非常非常大的dict),它有:

'orderItems': {
    'entries': [{
        'links': {
             'order': {
                'href': 'https: //api-latest.wdpro.xxxxx.com/booking-servicx/xxxxx/154301425212-3420290-4070919-6588782'
            }

所以,orderItems是一个dict,里面有一个列表,里面有entries,我需要得到的是href里面的order

我得到的列表是:orderlink = json_response["orderItems"]["entries"]

但我不太清楚如何通过列表找到href。也许用in。你知道吗

谢谢。你知道吗


Tags: httpscomapi标题列表orderlinkslatest
2条回答

要访问列表中的元素,必须使用数字索引,或者处理所有这些索引。你知道吗

最好的方法可能是在其中使用for循环,这将保证您将迭代列表上的所有条目:

hrefs  = []
for entry in orderlink:
   hrefs.append(entry["links"]["order"]["href"])

这将为您提供一个只包含所需URL的列表

假设您有JSON结构,我将使用以下代码来解决您的问题:

# Suppose that json_response is the whole dictionary
entry_list = json_response["orderItems"]["entries"]

# Now for each entry in the list, you need to get the "href" field
hrefs = []
for entry in entry_list:
    curr_href = entry["links"]["order"]["href"]
    hrefs.append(curr_href)

为了正确访问字段,您需要注意字典结构。在使用此代码之前,请仔细阅读Python3 documentation中的词典。你知道吗

相关问题 更多 >