我希望过滤下面的字典列表,以获得text
包含valid
的所有字典的pg_no
s。
test_response = [
{
'title': 'some value',
'pg_no': 1,
'text': 'Data is not valid'
},
{
'title': 'another title',
'pg_no': 2,
'text': 'some random text'
},
{
'title': 'last title',
'pg_no': 3,
'text': 'valid data'
}
]
下面的理解是有效的:
pg_nos = [d["pg_no"] for d in test_response if "valid" in d["text"]]
# [1, 3]
您可以尝试下面的代码
for i in test_response:
if "valid" in i['text']:
print(i['pg_no']) #Perform your required operation here I just used print for display
或者你也可以像这样使用列表推导式
[print(i['pg_no']) for i in test_response if "valid" in i['text']]