Home > Blockchain >  In list of dictionaries json format check particular word is available in value
In list of dictionaries json format check particular word is available in value

Time:10-15

I wish to filter the list of dictionaries below, to get the pg_nos for all dictionaries whose text contains valid.

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'
    }
]

CodePudding user response:

The following comprehension works:

pg_nos = [d["pg_no"] for d in test_response if "valid" in d["text"]]
# [1, 3]

CodePudding user response:

You can try the following code

    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

Or you can also use list comprehension like this

    [print(i['pg_no']) for i in test_response if "valid" in i['text']]
  • Related