Created
July 19, 2022 08:43
-
-
Save blacksmithop/64fbcfdc3b662a7f1fd10ea18924abc6 to your computer and use it in GitHub Desktop.
Get key with closest match* when accessing a dict item by key, otherwise return the 'first' key
This file contains hidden or 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
| class mdict(dict): | |
| def __missing__(self, key): | |
| keys = list(self.keys()) | |
| return next(in_key for in_key in keys if key in in_key) or keys[0] | |
| if __name__ == "__main__": | |
| item = mdict() | |
| item["abc"] = 123 | |
| item["bcd"] = 25 | |
| key = "ab" | |
| # print("dict", item) | |
| # print("key", key) | |
| print(item[key]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment