Search code examples
pythonintegerkey-value-coding

Converting dict values to integers when not all values are integers python


I have this code that gives me lists with keys:values. Firstly i'm accessing the 'symbol' key to filter everything but the lists which 'symbol' values end with ***BTC. Secondly I'm trying to access the 'quoteVolume' key and filter out all lists that have a value below e.g 100. The problem arises here since the list values are both strings and numbers and within the strings are both letters and numbers. And the value of 'quoteVolume' is a string.

Code:

import requests

#gets list with key and value data for all ticker pairs
data = requests.get('https://www.binance.com/api/v3/ticker/24hr')
dataJson = data.json()

#takes value from key 'symbol', can now search for certain symbols
dataDictionary = {d['symbol'] : d for d in dataJson}

#filters out everything but pairs that end with ***BTC
BTC_markets = dict(filter(lambda pair: pair[0][-3:] == 'BTC', dataDictionary.items()))

#filters lists with < 100 quoteVolume
high_volume_BTC_markets =  dict(filter(market_filter(['quoteVolume']),BTC_markets.items()))

print('Active high volume BTC Markets: ')
pprint(high_volume_BTC_markets)

The lists are about 100x and 1 looks like this

BTC_markets output:

 'STMXBTC': {'askPrice': '0.00000023',
             'askQty': '58640610.00000000',
             'bidPrice': '0.00000022',
             'bidQty': '130870153.00000000',
             'closeTime': 1594290726823,
             'count': 2842,
             'firstId': 66352,
             'highPrice': '0.00000024',
             'lastId': 69193,
             'lastPrice': '0.00000022',
             'lastQty': '2109909.00000000',
             'lowPrice': '0.00000022',
             'openPrice': '0.00000022',
             'openTime': 1594204326823,
             'prevClosePrice': '0.00000022',
             'priceChange': '0.00000000',
             'priceChangePercent': '0.000',
             'quoteVolume': '162.70619311',
             'symbol': 'STMXBTC',
             'volume': '713198749.00000000',
             'weightedAvgPrice': '0.00000023'},

So how can I transform all the lists quoteVolumevalue from str to ìnt without getting an error because of not all strings can be turned into numbers?

I'm very new to this and have been searching for a good couple of days before posting, I've tried different methods which i've encountered but havent found anything that works.

Thanks in advance!


Solution

  • def convert_to_int(d):
        for k, v in d.items():
            if isinstance(v, dict):
                convert_to_int(v)
            else:
                try:
                    d[k] = int(float(v)) # or just float(v) for floating point conversion:
                except Exception:
                    pass # ignore conversion errors and keep original value
    
    convert_to_int(BTC_markets)
    print(BTC_markets)
    

    Now to get a list of all quoteVolume values in the topmost dictionaries:

    quoteVolumes = [(k, BTC_markets[k]['quoteVolume']) for k in BTC_markets]
    filtered_quoteVolumes = filter(lambda item: item[1] >= 100, quoteVolumes)
    new_dict = dict(filtered_quoteVolumes)