Home > OS >  Is there a way in Robot Framework/Python to filter a list of dictionaries using regular expressions?
Is there a way in Robot Framework/Python to filter a list of dictionaries using regular expressions?

Time:08-24

I have the below list. I want to be able to filter this list of dictionaries with regular expressions.

list = [{'age': 20,'firstname':'John', 'lastname': 'Smith'}, {'age': 25,'firstname':'Joy', 'lastname': 'Jones'}, {'age': 30,'firstname':'Bill', 'lastname': 'Lee'}]

For example, i want the following outcome of:

matches = [{'age': 20,'firstname':'John', 'lastname': 'Smith'}, {'age': 25,'firstname':'Joy', 'lastname': 'Jones'}]

How can i do this within robot framework/python using the regexp of J.*.

CodePudding user response:

You can do something like this,

In [33]: [item for item in lst if re.match(r"J*", item["firstname"]).group()]

Out[33]: [{'age': 20, 'firstname': 'John', 'lastname': 'Smith'},
          {'age': 25, 'firstname': 'Joy', 'lastname': 'Jones'}]

CodePudding user response:

Expanding on @Rahul K P this is how it would look in robot framework.

***Variables***
${value}          [{"age": 20,"firstname":"John", "lastname": "Smith"}, {"age": 25,"firstname":"Joy", "lastname": "Jones"}, {"age": 30,"firstname":"Bill", "lastname": "Lee"}]

*** Test Cases ***  
test 
    ${json_value}=    Evaluate    json.loads("""${value}""")    json
    ${result}=    Evaluate    [item for item in ${json_value} if re.match(r"J*", item["firstname"]).group()]    re
    Log    ${result}
  • Related