python - How to retrieve dicts from a list of dicts using wildcard key value -
i have large list of dictionaries, each dict has key:value normal. want grab dicts match particular wildcard key value name key in example below.
for example, if values of name keys below in format a_b_c_d (e.g. john_michael_joseph_smith), how grab dicts searching 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}...]
your patterns appear use unix filename patterns; * matching number of characters. can use fnmatch.fnmatch() function produce filter:
>>> fnmatch import fnmatch >>> fnmatch('john_michael_joseph_smith', 'john*smith') true >>> fnmatch('john_michael_joseph_smith', 'john_michael*') true you use filter in list comprehension produce new list of matching dictionaries, testing each dictionary['name'] value against pattern:
from fnmatch import fnmatch def namesearch(pattern, dictionaries): return [d d in dictionaries if fnmatch(d['name'], pattern)] here namesearch returns list dictionaries 'name' value matches given pattern:
matched = namesearch('john*smith', mylist)
Comments
Post a Comment