-4

I need to iterate a list over a list for an API, changing a value for it and print out the results.

my_endpoint =  [
  '/this/is/endpoint/a',
  '/this/is/endpoint/b',
  '/this/is/endpoint/c',
  '/this/is/endpoint/d',
  '/this/is/endpoint/e',
  '/this/is/endpoint/f']

change_value = ['1','185','454']

I want to change the "endpoint" section in my_endpoint using values from change_value. The results I want are below:

'/this/is/1/a',
'/this/is/1/b',
'/this/is/1/c',
'/this/is/1/d',
'/this/is/1/e',
'/this/is/1/f']


'/this/is/185/a',
'/this/is/185/b',
'/this/is/185/c',
'/this/is/185/d',
'/this/is/185/e',
'/this/is/185/f']


'/this/is/454/a',
'/this/is/454/b',
'/this/is/454/c',
'/this/is/454/d',
'/this/is/454/e',
'/this/is/454/f']
xxyyzz
  • 1

1 Answers1

0

See:


my_endpoint =  [
  '/this/is/endpoint/a',
  '/this/is/endpoint/b',
  '/this/is/endpoint/c',
  '/this/is/endpoint/d',
  '/this/is/endpoint/e',
  '/this/is/endpoint/f']

change_value = ['1','185','454']

new_lists = {}  # dict to hold lists of new values
for line in my_endpoint:  # iterate through lines in results from API
    for value in change_value:  # iterate through list of new values
        # check if value is in dict,
        # this could be done at the time of creating the dict but this makes it dynamic
        if value not in new_lists:
            new_lists[value] = []  # add key to dict with empty list as the value
        # Use str replace to swap "endpoint" with <value>
        # add the new line to a list in the dict using the value as the key
        new_lists[value].append(line.replace("endpoint", value))

Results:

new_lists{
'1': ['/this/is/1/a',
       '/this/is/1/b',
       '/this/is/1/c',
       '/this/is/1/d',
       '/this/is/1/e',
       '/this/is/1/f'
],
'185': ['/this/is/185/a',
         '/this/is/185/b',
         '/this/is/185/c',
         '/this/is/185/d',
         '/this/is/185/e',
         '/this/is/185/f'
],
'454': ['/this/is/454/a',
         '/this/is/454/b',
         '/this/is/454/c',
         '/this/is/454/d',
         '/this/is/454/e',
         '/this/is/454/f'
]}
  • Thank you technoman5000. The dict did not work for my purpose so I had to tweak it to use a list instead but the nested loops worked great. – xxyyzz Mar 25 '19 at 17:49