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.

Max
  • 245
  • 3
  • 10
  • Possible duplicate of [How do I check if a given Python string is a substring of another one?](https://stackoverflow.com/questions/5143769/how-do-i-check-if-a-given-python-string-is-a-substring-of-another-one) – Rakesh Aug 09 '19 at 07:06
  • Could you explain why question is downvoted? – Max Aug 09 '19 at 12:56
  • Sorry I do not know...I did not downvote – Rakesh Aug 09 '19 at 12:57

2 Answers2

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']]
jure
  • 492
  • 5
  • 8
  • 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. – Max Aug 09 '19 at 12:16
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]
Zeecka
  • 51
  • 3