Search code examples
pythonpython-3.xpagerduty

How to store multiple python dictionaries or merge in a loop and return?


I am trying to get the pagination results of two pages but return is exiting loop and displays only one result from a page.

Is there a way to store or merge them?

  def incidents():
        m = True
        limit = 50
        offset = 0

        while m == True:
            url = f"{URL}/incidents"
            params = {
                "statuses[]": "resolved",
                "include[]" : 'channel',
                "limit"     : limit,
                "offset"    : offset,
                "total"     : "true",
            }
            r = requests.get(url, headers=headers, params=params)
            data = r.json()

            offset += 50
            print(offset, (r.text))
            more = False # Set deliberately for easier understanding

        return data

The offset, (r.text) output looks like -

50 {"incidents":[{"incident_number":1,"title":"crit server is on fire" ....


100 {"incidents":[{"incident_number":54,"title":"ghdg","description":"ghdg",....

Return only displays below and not the other one. There should be a way like use a generator for example? So we can merge them both and store in data variable so data can be returned?

100 {"incidents":[{"incident_number":54,....


Solution

  • I believe you could store the results in your own list:

    incidents = []
    

    and then

    data = r.json()
    for element in data['incidents']:
        incidents.append(element)
    

    Edited for clarity - that way you're gathering all incidents in a single object.