Searching a list of dictionaries without FOR loop

1,602 views
Skip to first unread message

Trey Duskin

unread,
Sep 1, 2014, 10:26:56 AM9/1/14
to robotframe...@googlegroups.com
Hi all,

I have a list of dictionaries (parsed out of JSON, so if there are better libraries for handling this I'm open) that I am trying to search to find if one key matches a value.  For example, my list of dictionaries looks like this:

[
   { 'id': '123', 'content': 'abcd', 'other': 'blah'},
   { 'id': '345', 'content': 'asjh', 'other': 'blah'},
   { 'id': '567', 'content': 'dsss', 'other': 'blah'},
   { 'id': '789', 'content': 'ddd', 'other': 'blah'},
   { 'id': '901', 'content': 'd', 'other': 'blah'},
]

I would like to get the dictionary from this list whose 'id' value matches '123' but I don't want to use the FOR loop inside of an RF keyword.  Are there any existing libraries (some way of using Collections, maybe) that will let me do this?  I don't want to have to go down the road of writing my own library just for this case if I don't have to.

Thanks in advance,
Trey

Trey Duskin

unread,
Sep 1, 2014, 11:22:42 AM9/1/14
to robotframe...@googlegroups.com
Hi all,

I actually thought about this some more and remembered there was an Evaluate keyword, and that python has a filter() function.  I was able to accomplish what I needed with this one-liner (given the previous example data in ${list}:

${found}  Evaluate  filter(lambda x: x['id'] == '123', ${list})

This will return a list of dictionaries which match the id I'm looking for.  This has the added benefit of finding multiple matches, which is something I'd have to do anyway.

Anyway, I hope this helps someone who is trying to do the same thing.

All the best,
Trey

Janne Härkönen

unread,
Sep 2, 2014, 11:31:18 AM9/2/14
to tr...@wilcoweb.net, robotframework-users
Hello Trey,


On Mon, Sep 1, 2014 at 6:22 PM, Trey Duskin <tr...@wilcoweb.net> wrote:
Hi all,

I actually thought about this some more and remembered there was an Evaluate keyword, and that python has a filter() function.  I was able to accomplish what I needed with this one-liner (given the previous example data in ${list}:

${found}  Evaluate  filter(lambda x: x['id'] == '123', ${list})

 While this solution is pretty neat, and it works, I'd definitely consider putting these kinds of things in a custom test library. Additionally, I think the whole community could benefit from a dedicated JSON library, which AFAIK does not exist.

--Janne 
Reply all
Reply to author
Forward
0 new messages