Home > database >  Better way to fill out dict?
Better way to fill out dict?

Time:10-13

I'm using python with the binance.client wrapper. I'm gathering all of the BTC trade pairs from the exchange and wanting to create a simple dict with tradepair: price. I have figured a way to do this but it seems clunky to me and takes a minute or so to run. I'm currently a programming student just getting started with python as well as some other languages. Is there a better way to do it than this?

def BTCPair():
    BTCPair = []
    BTCPrice = []
    BTCPairAndPrice = {}
    exchange_info = client.get_exchange_info()
    for s in exchange_info['symbols']:
        if 'BTC' in (s['symbol'])[-3:]:
            BTCPair.append(s['symbol'])
            BTCPrice.append(client.get_avg_price(symbol=s['symbol'])['price'])
    for i in range(len(BTCPair)):
        BTCPairAndPrice[BTCPair[i]] = BTCPrice[i]
    return BTCPairAndPrice

CodePudding user response:

I don't understand why you are using two loops; one to put the data into lists, and another to convert those lists into a dictionary - why not just construct the dictionary directly?

You could just construct your dictionary directly using a comprehension:

BTCPairAndPrice = {
    s['symbol']: client.get_avg_price(symbol=s['symbol'])['price']
    for s in exchange_info['symbols']
    if 'BTC' in (s['symbol'])[-3:]
}

The way the dictionary is constructed is unlikely to have a big impact on performance, but not iterating through all the data twice should have an impact if there is a lot of data.

Also consider that contacting a web service is also likely to take some time, so contacting the exchange might be the slowest part.

CodePudding user response:

First of all, for i in range(len(BTCPair)) is an antipattern. You could instead iterate over those zipped together.

But we don't actually need to do that either! Rather than creating two lists and then iterating over them to fill in your dictionary, you could create everything in one go with a dictionary comprehension. Also, a cleaner way to check the end of a string is endswith().

def btc_pair():
    symbols = client.get_exchange_info()['symbols']
    return {
        symbol['symbol']: client.get_avg_price(symbol=symbol)['price']
        for symbol in symbols
        if symbol['symbol'].endswith('BTC')
    }

This probably will run a little bit faster, but I doubt that the dictionary creation itself is the real performance bottleneck in your code.

  • Related