Home > Mobile >  Looping through a list and find all the ID of the properties:
Looping through a list and find all the ID of the properties:

Time:10-27

i'm a newbie in Python. I have a project of collecting data on API call. i've successfully call for a list of data (List of users and other infos such as ID, name,.....) based on this post: Loop through an object's properties and get the values for those of type DateTime. The code i make looks like this:

import requests
import json
def get_all_time_entries():

url_address = "my url"  
headers = {
    "Authorization": "Bearer "   "my api",
    "Harvest-Account-ID": "my ID"
}


all_time_entries = []

# loop through all pages and return JSON object
for page in range(1, 15):

    url = "my url" str(page)
    response = requests.get(url=url, headers=headers).json()        
    all_time_entries.append(response)       
    page  = 1

# prettify JSON
data = json.dumps(all_time_entries, sort_keys=True, indent=4)

return data
print(get_all_time_entries())

I've manage to call a list of users of this format:

{
        "created_at": "2021-01-23T22:34:30 07:00",
        "email": "someone.gmail.com",
        "id": 11111,
        "integration_id": null,
        "login_id": "someone.gmail.com",
        "name": "Name of user",
        "short_name": "Name of user",
        "sis_import_id": 111,
        "sis_user_id": "Name of user",
        "sortable_name": ", Name of user"
    },

Now i want to make a loop to get all the "ID" property in the "all_time_entries()" list and put them in another list. Is it possible? or is there any solution for this? Thanks alot.

CodePudding user response:

Remove the "page = 1" at the end of the loop each iteration the value of page is assigned at beginning to its corresponding range value, to get all ids do this:

all_ids = [i['id'] for i in all_time_entries]

CodePudding user response:

The following function will do what you want

get_ids_from_time_entries(time_entries):
    ids = []

    for entry in time_entries:
        ids.append( entry['id'] )

    return ids

And then you would use it like so

time_entries = get_all_time_entries()
ids = get_ids_from_time_entries(time_entries)
print(ids)
  • Related