Home > Back-end >  Python For Loop to separate JSON responses and combine into list
Python For Loop to separate JSON responses and combine into list

Time:01-25

I have CMC's API in order to retrieve the first 2 currencies.

From here, I get the responses and attempted to put them into a list, but instead each JSON response gets put into its own list.

print()
#print('Part 3 - List of SYMBOLS appended to URL: ')
for symbol in nameList:
    urlList = []
    urlSymbol = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/info?symbol={}'.format(symbol)
    urlList.append(urlSymbol)
    #print(urlList)

    
    for url in urlList:
        req = requests.get(url, headers=headers)
        #print(req)
        allResponses = req.content
        #print(allResponses)
        test = []
        test.append(allResponses)
        print(test)
        print(type(test))

Ouput:

[b'{"status":{"timestamp"...]
[b'{"status":{"timestamp"...]

So the For loop does work inserting each JSON response into its own list but how would I have these both combine into 1 list as so:

test = [b'{"status":{"timestamp"...}, b'{"status":{"timestamp"...}]

CodePudding user response:

The reason it creates a new list is because the test = [] line is inside your for loop. This creates a brand new list each time you loop. Thus when you call append it adds an item to the list but then that list is destroyed/a new one is created on the next url iteration.

To fix it move the initialization of that list above your inner for loop so that inside the for loop you append to the test list without recreating it on each iteration.

test = []
for url in urlList:
        req = requests.get(url, headers=headers)
        allResponses = req.content
        test.append(allResponses)
print(test)
  • Related