I need to generate a hash from a tuple. Ideally I would have liked to able to do it from a list, but that's not possible. I need something that I can use the hash to generate back the tuple, to finally access the original list with the items in the right order (items will be strings).
Here's what I'm trying to hash
l = ['x', 'y', 'z']
t = tuple(l)
I tried using hash(), but that ended up not giving the same hash across Python sessions, which is something I need.
I need the hash because I want to create a file based off that list with the hash as the filename. I then want to lookup the file name and be able to access the list items (in the correct order) using just the hash.
My understanding is that this is possible, but I could be wrong. Any ideas?
You can use MD5, which is fast, and will always give you the same result for the same input.
import hashlib
t = ('x', 'y', 'z')
m = hashlib.md5()
for s in t:
m.update(s.encode())
fn = m.hexdigest() # => 'd16fb36f0911f878998c136191af705e'
As user2357112 says, you cannot reconstruct l from fn; but if l was saved in a file that bears the MD5 hash, you will be able to read it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With