当并非所有值都是整数时将字典值转换为整数 python

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

我有这段代码,它为我提供了带有 keys:values 的列表。首先,我正在访问 'symbol' 键来过滤所有内容,但 'symbol' 值以 ***BTC 结尾的列表除外。其次,我正在尝试访问 'quoteVolume' 键并过滤掉所有值低于 100 的列表。问题出现在这里,因为列表值既是字符串又是数字,而字符串中既是字母又是数字。而'quoteVolume'的值是一个字符串。

代码:

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)

列表大约是 100 倍,其中 1 个看起来像这样

BTC_markets 输出:

 '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'},

那么我怎样才能将所有列表 quoteVolume 的值从 str 转换为 ìnt 而不会出现错误,因为并非所有字符串都可以转换为数字?

我对此很陌生,在发帖前已经搜索了好几天,我尝试了我遇到的不同方法,但没有找到任何有效的方法。

提前致谢!

quoteVolume 看起来像 '162.70619311' 是一个包含浮点数的字符串所以你不能直接使用 int(),你需要先使用 float() 像这样:

value = int(float(your_quote_volume))

这样做是为了让它变成 162。如果您需要保留小数点,则不要执行 int().

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)

现在获取最顶层词典中所有 quoteVolume 值的 list

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)