Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement a fuzzy search across each value of a dictionary in a multiple dictionary list?

I have a list of dictionaries. I am trying to implement a 'fuzzy' search of said dictionary values and have the full dictionary returned.

Therefore, if I have a list of dicts as follows:

[
{"Name":"Arnold", "Age":"52", "Height":"160"}, 
{"Name":"Donald", "Age":"52", "Height":"161"}, 
{"Name":"Trevor", "Age":"22", "Height":"150"}
]

A search term of "nol" should return

{"Name":"Arnold", "Age":"52", "Height":"160"} 

While a search term of "52" should return:

{"Name":"Arnold", "Age":"52", "Height":"160"} 
{"Name":"Donald", "Age":"52", "Height":"161"}

I understand that I can search for values at a particular key using iteritems, I'm just not clear on how to search across all key/values in a dictionary (without knowing the keyname), and then return said dictionary if there is a match in any. Is this possible in python?

like image 252
user714852 Avatar asked Mar 23 '23 17:03

user714852


1 Answers

You can use something like

>>> l = [
... {"Name":"Arnold", "Age":"52", "Height":"160"}, 
... {"Name":"Donald", "Age":"52", "Height":"161"}, 
... {"Name":"Trevor", "Age":"22", "Height":"150"}
... ]
>>>
>>> [d for d in l if any("nol" in v for v in d.values())]
[{'Age': '52', 'Name': 'Arnold', 'Height': '160'}]
>>>
>>> [d for d in l if any("52" in v for v in d.values())]
[{'Age': '52', 'Name': 'Arnold', 'Height': '160'}, {'Age': '52', 'Name': 'Donald', 'Height': '161'}]
like image 58
arshajii Avatar answered Apr 26 '23 12:04

arshajii