如何在字典列表中查找字符串作为键值的一部分?

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

在字典列表中我想找到包含字符串的键值。

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

s = 'BTC'

我想在符号值中查找包含字符串的字典。 例如: 在市场符号中搜索 s 应该 return 以下字典列表:

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

如能提供任何帮助,我们将不胜感激。

您可以执行以下任一操作:

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

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

以上代码应该 return 包含您要查找的值的市场列表。您也可以将其压缩成一个衬里:

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