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?
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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With