Home > OS >  for loop print only last value from dict in live market
for loop print only last value from dict in live market

Time:09-06

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())) 

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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))) 
  • Related