Alexandre Simões
Alexandre Simões

Reputation: 1294

Filter dictionary list by text in string

I have a list of dictionaries and need to filter them by a list of strings.

Right now I have this:

projects = [{u'CustomerName': u'abc', u'Projectname': u'Contract A full'},
{u'CustomerName': u'bcd', u'Projectname': u'Contract A medium'},
{u'CustomerName': u'cde', u'Projectname': u'Contract B full'},
{u'CustomerName': u'def', u'Projectname': u'Contract B medium'}]

filter = ['B', 'full']

return [p for p in projects if p['ProjectName'] in filter]

The result I need is:

[{u'CustomerName': u'abc', u'Projectname': u'Contract A full'},
{u'CustomerName': u'cde', u'Projectname': u'Contract B medium'},
{u'CustomerName': u'cde', u'Projectname': u'Contract B full'}]

However it returns nothing. Only if I specify the entire string:

filter = ['Contract A full', 'Contract B full']

Thank's for the help.

Upvotes: 0

Views: 733

Answers (2)

Yunkai Xiao
Yunkai Xiao

Reputation: 301

The marked answer is a very elegant way out, especially for the "any" part.

Here is another way using regular expression:

import re
[p for p in projects if re.match(".*(B|full).*",p["Projectname"])]

".*" basically means anything any occurrence, this regex implies you're looking for the occurrence of "B" or "full" with anything in front and behind it.

Though you might encounter some cases where it would match unexpected things such as "Contract fuller-house medium" or some other things, regex does work on simple cases like the one you presented without too much trouble.

Upvotes: 1

jpp
jpp

Reputation: 164783

This is one way, assuming you are looking for ProjectNames containing 'full':

[p for p in projects if 'full' in p['ProjectName']]

Or if you need containing 'B' or 'full':

[p for p in projects if any(i in p['ProjectName'] for i in ('B', 'full'))]

Upvotes: 3

Related Questions