Python API - Filter result by element

I'm working with CoinGecko APIs (https://www.coingecko.com/en/api/documentation) but I have a problem in selecting the call element i need. The code is the one below:

from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()

mhccex = cg.get_coin_ticker_by_id(id = 'metahash', exchange_ids='cex')

and the output:

{
  "name": "#MetaHash",
  "tickers": [
    {
      "base": "MHC",
      "target": "BTC",
      "market": {
        "name": "KuCoin",
        "identifier": "kucoin",
        "has_trading_incentive": false
      },
      "last": 1.448e-7,
      "volume": 9588907.27145872,
      "converted_last": {
        "btc": 1.448e-7,
        "eth": 0.00000207,
        "usd": 0.0051756
      },
      "converted_volume": {
        "btc": 1.388474,
        "eth": 19.865387,
        "usd": 49628
      },
      "trust_score": "green",
      "bid_ask_spread_percentage": 1.302262,
      "timestamp": "2022-01-23T12:40:31+00:00",
      "last_traded_at": "2022-01-23T12:40:31+00:00",
      "last_fetch_at": "2022-01-23T12:40:31+00:00",
      "is_anomaly": false,
      "is_stale": false,
      "trade_url": "https://www.kucoin.com/trade/MHC-BTC",
      "token_info_url": null,
      "coin_id": "metahash",
      "target_coin_id": "bitcoin"
    },
    {
      "base": "MHC",
      "target": "USDT",
      "market": {
        "name": "KuCoin",
        "identifier": "kucoin",
        "has_trading_incentive": false
      },
      "last": 0.005182,
      "volume": 8777124.90264143,
      "converted_last": {
        "btc": 1.45387e-7,
        "eth": 0.00000208,
        "usd": 0.00519658
      },
      "converted_volume": {
        "btc": 1.276079,
        "eth": 18.257313,
        "usd": 45611
      },
      "trust_score": "green",
      "bid_ask_spread_percentage": 0.944305,
      "timestamp": "2022-01-23T12:40:30+00:00",
      "last_traded_at": "2022-01-23T12:40:30+00:00",
      "last_fetch_at": "2022-01-23T12:40:30+00:00",
      "is_anomaly": false,
      "is_stale": false,
      "trade_url": "https://www.kucoin.com/trade/MHC-USDT",
      "token_info_url": null,
      "coin_id": "metahash",
      "target_coin_id": "tether"
    },
]
}

I need to access the 'last' field related to the ticker 'target':USDT. The following code doesn't work because the order of 'tickers' changes at each API call randomly:

mhccex = cg.get_coin_ticker_by_id(id = 'metahash', exchange_ids='cex')['tickers'][1]['last']

Solution 1:

You can use filter to find the item in the tickers list for the given target:

from pycoingecko import CoinGeckoAPI

cg = CoinGeckoAPI()

mhccex = cg.get_coin_ticker_by_id(id = 'metahash', exchange_ids='cex')['tickers']

results = list(filter(lambda item: item['target'] == 'USD', mhccex))

print(results[0]['last'])

The results will be a list, but presumably for any given coin and currency there will be only one exchange combination.