Home > Software engineering >  Python - Append to Docitionary List
Python - Append to Docitionary List

Time:11-11

I have a dictionary with a list that appears like this:

{'subscription_id_list': ['92878351', '93153640', '93840845', '93840847'.......]

There will be up to 10,000 entries in the list for each call to the API. What I want to do is loop and append the list so when complete, my {'subscription_id_list'} contains everything.

Any thoughts?

CodePudding user response:

It sounds like you have something like

for api_request in some_structure:
    response = get_remote_results(api_request)
    # response structure is single-key dict,
    # key is 'subscription_id_list'; value is list of str of int
    # i.e. {'subscription-id-list': ['1234','5678',....]}

and you want some complete dict to contain the list of all values in the various responses. Then use list.extend:

complete_sub_id_list = []
for api_request in some_structure:
    response = get_remote_results(api_request)
    complete_sub_id_list.extend(response['subscription_id_list'])

As noted in a comment, if you're making API requests to a remote server or resource (or even something dependent on local I/O), you're likely going to want to use asynchronous calls; if you're not already familiar with what that means, perhaps aiohttp and/or asyncio will be quite helpful. See e.g. this Twilio guide for more info. TL;DR you could see 5-30x speedup as opposed to using synchronous calls.

  • Related