Skip to content

Instantly share code, notes, and snippets.

@blacksmithop
Created July 19, 2022 08:43
Show Gist options
  • Select an option

  • Save blacksmithop/64fbcfdc3b662a7f1fd10ea18924abc6 to your computer and use it in GitHub Desktop.

Select an option

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
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