2

I've got a problem with a list of dictionaries. I need to get the price of Bitcoin from the following list (the list is longer but I cut it for this message):

tickerlist = [{'symbol': 'ETHBTC', 'price': '0.03756600'},
            {'symbol': 'LTCBTC', 'price': '0.00968200'},
            {'symbol': 'BNBBTC', 'price': '0.00164680'},
            {'symbol': 'NEOBTC', 'price': '0.00230000'},
            {'symbol': 'QTUMETH', 'price': '0.01587100'},
            {'symbol': 'EOSETH', 'price': '0.01875000'},
            {'symbol': 'SNTETH', 'price': '0.00013221'},
            {'symbol': 'BNTETH', 'price': '0.00445000'},
            {'symbol': 'BCCBTC', 'price': '0.07908100'},
            {'symbol': 'GASBTC', 'price': '0.00064300'},
            {'symbol': 'BNBETH', 'price': '0.04389800'},
            {'symbol': 'BTCUSDT', 'price': '3954.63000000'}]

The objective is to get the following outcome:

BTCUSDT = 3954.63000000

I wrote the following noob code to reach my goal:

x = tickerlist[11]
BTCUSDT = x["price"]
print(BTCUSDT)

Since the order in the list (position 11) of the dictionary I'm interested in: {'symbol': 'BTCUSDT', 'price': '3954.63000000'} may change in the future, I wanted to know if there is a function where I just insert 'BTCUSDT' and it gives me back the price ('3954.63000000').

I looked on stackoverflow and I found the comprehensive list, but I didn't manage to make it work.

Do you have any ideas?

I'm using Python 3.7.1

Carl
  • 211
  • 1
  • 3
  • 11

3 Answers3

2

You can use the next function with a generator expression that iterates through tickerlist to find a matching symbol:

try:
    BTCUSDT = next(ticker['price'] for ticker in tickerlist if ticker['symbol'] == 'BTCUSDT')
except StopIteration:
    raise RuntimeError('No matching symbol found')
blhsing
  • 91,368
  • 6
  • 71
  • 106
2

You can use dict instead of list:

ticker_dict =  {
    'ETHBTC': {'price': '0.03756600'},
    'LTCBTC', {'price': '0.00968200'}
}

Either do something like this:

my_currency = list(filter(lambda list_element: list_element['symbol'] == your_symbol, tickerlist))[0]
Mikhail Sidorov
  • 1,325
  • 11
  • 15
0

Try the following:

index = [ i for i in range(len(lst)) if lst[i]['symbol'] == 'BTCUSDT' ][0]

print( tickerlist[index]['symbol'], '=', tickerlist[index]['price'] )       
Siddharth Satpathy
  • 2,737
  • 4
  • 29
  • 52