0

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.

3

2 Answers 2

1
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']]
Sign up to request clarification or add additional context in comments.

1 Comment

I compared timing on your solution and Zeecka. On list with 1800 dictionaries time for your solution was 0.0004906654357910156 and for Zeecka solution - 0.0015139579772949219 so I marked your solution as accepted answer. Thank you both for help.
0

You can do either:

found = []
for m in markets:
    for l in m.values():
        if s in l:
            found.append(m)

or

found = [m for m in markets for l in m.values() if s in l]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.