Skip to content

Instantly share code, notes, and snippets.

@brettvitaz
Created October 2, 2022 00:54
Show Gist options
  • Save brettvitaz/0f0d55f3e243eeb0a6dba7950790ccb6 to your computer and use it in GitHub Desktop.
Save brettvitaz/0f0d55f3e243eeb0a6dba7950790ccb6 to your computer and use it in GitHub Desktop.
Python Hashing for List and Dict types
def hash_list(list_: list) -> int:
__hash = 0
for i, e in enumerate(list_):
__hash = hash((__hash, i, hash_item(e)))
return __hash
def hash_dict(dict_: dict) -> int:
__hash = 0
for k, v in dict_.items():
__hash = hash((__hash, k, hash_item(v)))
return __hash
def hash_item(item) -> int:
if hasattr(item, '__hash__') and callable(item.__hash__):
try:
return hash(item)
except TypeError:
pass
if isinstance(item, (list, set, tuple)):
return hash_list(list(item))
elif isinstance(item, dict):
return hash_dict(item)
else:
raise TypeError(f'unhashable type: {item.__class__}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment