'Iterating through a list inside a dictionary in Python for an API call

I am pretty new to Python. I have a dictionary that looks like this, with a list inside:

"detail": {'items': [['123','item1'],['345','item2']]

and I am trying to use the first item in the list for an API call

    for x in y["detail"]["items"]:
        url = "https://link/list-of-items/" + x[0]

    payload = {}
    headers = {
        'Authorization': 'Bearer ' + (parameter['Parameter']['Value'])
    }
        
    response = requests.request("GET", url, headers=headers, data=payload)
    json_object = json.loads(response.text)

I have been trying to get the response to be the details of both item1 and item2 using x[0], the first index. How would I go about in doing that?



Solution 1:[1]

In each iteration of the for loop, the url variable is reassigned a new value. Therefore after the loop is finished, url's value is https://link/list-of-items/345.

As @Thomas mentioned, you probably need to send multiple requests (one per item), and therefore all the code needs to go into the for loop.

In addition, it is important to have meaningful variable names to get readable code.

Putting it all together:

for item in iteams_detail["detail"]["items"]:
    url = "https://link/list-of-items/" + item[0]
    payload = {}
    headers = {'Authorization': 'Bearer ' + (parameter['Parameter']['Value'])}
    response = requests.request("GET", url, headers=headers, data=payload)
    json_object = json.loads(response.text)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eyal Golan