Reputation: 103
I have a large list of dictionaries, each dict has a key:value as normal. I want to grab all dicts that a match a particular wildcard key value for the name key in the example below.
For example, if the values of the name keys below are in the format A_B_C_D
(e.g. John_Michael_Joseph_Smith
), how would I grab all dicts searching for name values of format A*D
(e.g. John*Smith
?) Or format A_B*
(e.g. John_Michael*
) etc?
mylist=[{id:value,name:value,parent:value},
{id:value,name:value,parent:value},
{id:value,name:value,parent:value}...]
Upvotes: 0
Views: 986
Reputation: 1122122
Your patterns appear to use UNIX filename patterns; *
matching any number of characters. You can use the fnmatch.fnmatch()
function to produce a filter:
>>> from fnmatch import fnmatch
>>> fnmatch('John_Michael_Joseph_Smith', 'John*Smith')
True
>>> fnmatch('John_Michael_Joseph_Smith', 'John_Michael*')
True
You could use the filter in a list comprehension to produce a new list of matching dictionaries, testing each dictionary['name']
value against the pattern:
from fnmatch import fnmatch
def namesearch(pattern, dictionaries):
return [d for d in dictionaries if fnmatch(d['name'], pattern)]
Here namesearch
returns a list dictionaries whose 'name'
value matches the given pattern:
matched = namesearch('John*Smith', mylist)
Upvotes: 3