Ad

How To Get A Value From A List Of Dictionaries - Python 3.7.1

- 1 answer

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

Ad

Answer

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')
Ad
source: stackoverflow.com
Ad