How to seperate an exchange pair string returned from binance api into two strings

Viewed 28

I am getting market information from the Binance API and transform them in the following form by storing them in a dictionary:

    {"ETHBTC": 0.069587,
    "LTCBTC": 0.002675,
    "BNBBTC": 0.013776,
    "NEOBTC": 0.000427,
    "QTUMETH": 0.002141,
    "EOSETH": 0.000945,
    "SNTETH": 2.067e-05,
    "BNTETH": 0.000326,
    "BCCBTC": 0.079081,
    "GASBTC": 0.0001215,
    "BNBETH": 0.1979,
    "BTCUSDT": 19536.37,
    "ETHUSDT": 1359.3,
    "HSRBTC": 0.000414,
    "OAXETH": 0.0001778,
    "DNTETH": 2.801e-05,
    "MCOETH": 0.005772}

The problem is that the Binance API returns the pairs as a single string and i want to separate the currencies in order to be able to recognise them. But the number of characters each coin has is different so there is not a general rule in order to separate them. The form I want them to be is the following:

{
    "ETH-BTC": 0.069587,
    "LTC-BTC": 0.002675,
    "BNB-BTC": 0.013776,
    "NEO-BTC": 0.000427,
    "QTUM-ETH": 0.002141,
    "EOS-ETH": 0.000945,
    "SNT-ETH": 2.067e-05,
    "BNT-ETH": 0.000326,
    "BCC-BTC": 0.079081,
    "GAS-BTC": 0.0001215,
    "BNB-ETH": 0.1979,
    "BTC-USDT": 19536.37,
    "ETH-USDT": 1359.3,
    "HSR-BTC": 0.000414,
    "OAX-ETH": 0.0001778,
    "DNT-ETH": 2.801e-05,
    "MCO-ETH": 0.005772,

Is there a way for a program to put the dash between the coins in order to be recognisable?

Thanks!

1 Answers

Since all your strings start or end with either "ETH" or "BTC"

Considering you named your dictionary as data the following should work:

for key in list(data.keys()):
    if key.endswith("ETH") or key.endswith("BTC"):
        new_key = f"{key[:-3]}-{key[-3:]}"
    else:
        new_key = f"{key[:3]}-{key[3:]}"
    data[new_key] = data.pop(key)

output

print(data)
>>>
{'ETH-BTC': 0.069587,
 'LTC-BTC': 0.002675,
 'BNB-BTC': 0.013776,
 'NEO-BTC': 0.000427,
 'QTUM-ETH': 0.002141,
 'EOS-ETH': 0.000945,
 'SNT-ETH': 2.067e-05,
 'BNT-ETH': 0.000326,
 'BCC-BTC': 0.079081,
 'GAS-BTC': 0.0001215,
 'BNB-ETH': 0.1979,
 'BTC-USDT': 19536.37,
 'ETH-USDT': 1359.3,
 'HSR-BTC': 0.000414,
 'OAX-ETH': 0.0001778,
 'DNT-ETH': 2.801e-05,
 'MCO-ETH': 0.005772}
Related