Created
October 2, 2022 00:54
-
-
Save brettvitaz/0f0d55f3e243eeb0a6dba7950790ccb6 to your computer and use it in GitHub Desktop.
Python Hashing for List and Dict types
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 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