I have a Python list of strings, e.g. initialized as follows:
l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra']
I would like to test an input string against this list, and find the “closest string below it” and the “closest string above it”, alphabetically and case-insensitively (i.e. no phonetics, just a<b etc). If the input exists in the list, both the “below” and “above” should return the input.
Several examples:
Input | Below | Above
-------------------------------
bat | aardvark | cat
aaa | None | aardvark
ferret | dog | fish
dog | dog | dog
What’s the neatest way to achieve this in Python? (currently I’m iterating over a sorted list using a for loop)
To further clarify: I’m interested in simple dictionary alphabetical comparison, not anything fancy like Levenshtein or phonetics.
Thanks
This is exactly what the bisect module is for. It will be much faster than just iterating through large lists.
The above code assumes you’ve sanitized the input and list to be all upper or lower case. Also, I wrote this on my iPhone, so please do check for typos.