Search code examples
python-3.xdjango-2.1

How to find string as a part of key value in list of dict?


In list of dictionaries I would like to find key value containg string.

markets = [
    {'symbol': 'BTC/AUD', 'baseId': 'bitcoin'},
    {'symbol': 'USD/AUD', 'baseId': 'dollar'},
    {'symbol': 'EUR/AUD', 'baseId': 'euro'},
    {'symbol': 'ETH/BTC', 'baseId': 'eth'},
]

s = 'BTC'

I would like to find in symbol values dicts containing a string. For example: Searching for s in markets symbols should return folowing list of dicts:

found = [
    {'symbol': 'BTC/AUD', 'baseId': 'bitcoin'},
    {'symbol': 'ETH/BTC', 'baseId': 'eth'},
]

Any help you can give would be greatly appreciated.


Solution

  • found = []
    for market in markets:
        if s in market['symbol']:
            found.append(market)
    return found
    

    The above code should return a list of markets containing the value you're looking for. You can also condense this into a one liner:

    found = [market for market in markets if s in market['symbol']]