Last active
July 24, 2017 20:46
-
-
Save MattWoodhead/7483ef8a6ec78fe55abeb79e219fdcfe to your computer and use it in GitHub Desktop.
Simple case insensitive key matching for dictionaries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def caseless_dict_search(dictionary, search_string): | |
""" performs a case insensitive key search on a standard dictionary """ | |
# A dict matching lower case and actual case representations of the Keys | |
keys_dict = {k.casefold(): k for k in dictionary.keys()} | |
# Using the get() function to search dict with builtin error handling | |
return dictionary.get(keys_dict.get(search_string.lower(), None), None) | |
test_dict = {"A": 0, "B": 1, "c": 2, "d":3} | |
INPUT = "D" # Note case does not match any of the keys in the above dict | |
result = caseless_dict_search(test_dict, INPUT) | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment