I have a total number of tasks at 6716, and a dictionary consisting of a token as key and a length as item. What i need to do is to count up to the first length in the dictionary. In other words, if I have a total task of 6716 and dictionary = {'tok1':5121}, then I need to do something when iterating up to 5121. If the dictionary looks like: dictionary = {'tok1':5121, 'tok2':802, 'tok3':793}, then it would need to do something when iterating the first 5121, then it should do something else the next 802, and eventually do something else when iterating the next 793, which would all sum up to iterating to 6716.
I imagined that it would look something like the following:
num_tasks = 6716
dict = {'tok1':5121, 'tok2':802, 'tok3':793}
for i in range(num_tasks):
if i <= dict['tok1']
do something...
elif i > dict['tok1'] and i <= dict['tok1'] + dict['tok2']
do something...
elif i > dict['tok1'] + dict['tok2']
do something...
Although this in theory should work, it is not the most optimal way of looping, since we might have 1000's of tokens one day, and therefore I would need to add 1000's if statements, which isn't very scalable. Therefore, I need help to find a more dynamic way of looping like this.
CODE
list = ['tok1', 'tok2', 'tok3']
dict = {'tok1':5121, 'tok2':802, 'tok3':793}
nexts = iter(customerNumbers)
try:
for i in range(n_tasks): # n_tasks = 6716
single = file['xxx'][i]
test = file['xxx'][i]['number']
if test in custom:
self.params["skippages"] += 1
if test in customerNumbers: # customerNumbers is a list containing numbers of customers
url = self.url + f'customers/{next(nexts)}'
# Here i need to say that for the first 5121 in num_tasks, change token to the first item in the list containing tokens, then for the next 802 in num_tasks change token to 'tok2' from the list containing tokens etc.
# For example: if i <= 5121 then token = list[0], if i > 5121 and i < 5121+802 then change token = list[1] etc.
headers = {'X-AppSecretToken': self.secret_token, 'X-AgreementGrantToken': {token}, 'Content-Type': "application/json"}
pool.apply_async(request_put, args=(url, headers, self.params, json.dumps(single)))
except StopIteration:
pass
# wait for all tasks to complete:
pool.close()
pool.join()
def request_put(url, headers, params, single):
return requests.put(url=url, headers=headers, params=params, data=single)
tok_ii.etok1>tok2..do something...? Perhaps you will need 1000 if statements to get the right things done in each case.