9

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?

4
  • 3
    "I need something that I can use the hash to generate back the tuple" - then what you need isn't a hash. Hashes aren't designed to let you recover the original input. Commented Dec 27, 2018 at 4:30
  • Fair enough, what should I look into then? Commented Dec 27, 2018 at 4:31
  • @user2357112: Maybe it's the wording. The "In need the hash..." paragraph describes the use case better: hash as filename to retrieve the stored value from the file where the value is saved. Commented Dec 27, 2018 at 4:33
  • Related: stackoverflow.com/questions/64344515/… Commented Sep 19, 2022 at 7:35

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That last part was it, saving l inside of the file seems to be the way to go. Thanks!
.encode() is a method of str. So if your tuple elements are not strings, you would need to use str(s).encode() in your update line
4

No, this is not possible if your tuple contains strings and with the builtin hash().

The hash of strings are intentionally made variable across Python sessions, because in Python 3.4, it led to a potential security issue (PEP 456). In Python 3.5, this was fixed by making hashes of strings different in every Python session.

I recommend that you create a hashing function of your own so it's stable, or use some hashlib.

1 Comment

This would have saved me hours if I had discovered it earlier...
-1

Hash is theoretically irreversible. Encrypt seems to be want you want. For example, base64

================== update

base64 is encode technology.enter link description here

Maybe encrypt or encode is want you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.