for loop print only last value from dict in live market

Question:

try to print LTP data for more than one crypto in live market but printing only for one crypto.

import pandas as pd
import requests
import json

ltp_data= []

crypto = {"BTCUSDT",  "LTCUSDT", "DOGEUSDT"}
def live_ltp():
    for i in crypto:
        key = "https://api.binance.com/api/v3/ticker/price?symbol="
        url = key+i
        response = requests.get(url)
        Ltp = response.json()
        ltp_data.append(Ltp)
        return Ltp
while True:
    print(str(live_ltp())) 
Asked By: Shankar

||

Answers:

You have a return Ltp in the for loop so you will always just get a single response for the first item in the set of crypto id’s. You could instead do return lpd_data after the loop ends. But that creates a new problem – since you are updating a global list, it will just keep growing and growing.

Instead, write your function to take input parameters and return a locally-generated list.

import pandas as pd
import requests
import json

def live_ltp(crypto_ids):
    ltp_data = []
    for i in crypto_ids:
        key = "https://api.binance.com/api/v3/ticker/price?symbol="
        url = key+i
        response = requests.get(url)
        Ltp = response.json()
        ltp_data.append(Ltp)
    return ltp_data

crypto = {"BTCUSDT",  "LTCUSDT", "DOGEUSDT"}

while True:
    print(str(live_ltp(crypto))) 
Answered By: tdelaney

You have added the return statement at the end of loop because of which it’s executing only one time and returning only 1 data.

Instead,

import pandas as pd
import requests
import json

ltp_data= []

crypto = {"BTCUSDT",  "LTCUSDT", "DOGEUSDT"}
def live_ltp():
    responses = []
    for i in crypto:
        key = "https://api.binance.com/api/v3/ticker/price?symbol="
        url = key+i
        response = requests.get(url)
        Ltp = response.json()
        ltp_data.append(Ltp)
        responses.append(Ltp)
    return responses
while True:
    print(str(live_ltp()))

This will solve the problem.
Hope this helps you!!!
Please free to comment if you get any error in this and mark the answer as correct if it worked.

Answered By: sachin

return will exit your loop as soon as it is hit. If you bring your return statement outside of the loop, and have it return ltp_data (instead of the "LTP" json object) you should be able to get the items in the list you appear to be populating.

ltp_data= []

crypto = {"BTCUSDT",  "LTCUSDT", "DOGEUSDT"}
def live_ltp():
    for i in crypto:
        key = "https://api.binance.com/api/v3/ticker/price?symbol="
        url = key+i
        response = requests.get(url)
        Ltp = response.json()
        ltp_data.append(Ltp)
    return ltp_data

crypto_ltps = live_ltp()
print(crypto_ltps)
Answered By: SquatLicense

solution with dataframe in place.

you will need to pass empty dataframe to function: live_ltp(df_frame).

I would also use .json_normalize to set table in place properly.

import pandas as pd
import requests
import json


ltp_data = pd.DataFrame() # empty dataframe (not list) which will be updated in the function below
crypto = {"BTCUSDT",  "LTCUSDT", "DOGEUSDT"}

def live_ltp(df_frame):
    for i in crypto:
        key = "https://api.binance.com/api/v3/ticker/price?symbol="
        url = key+i
        response = requests.get(url)
        Ltp = response.json()
        ltp_df = pd.json_normalize(Ltp)
        ltp_df['time'] = pd.Timestamp.now()
        df_frame = pd.concat([df_frame, ltp_df], axis=0)
    return df_frame


while True:
    final_df = live_ltp(ltp_data) # passing empty dataframe to function
    final_df.to_excel('test.xlsx', index=False)
    print(final_df)
Answered By: NoobVB
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.