Reputation: 50362
What is a good way to get a hash from a group of values of different data types (in Python)?
The values need to be hashed in a consistent order. Values that need to be hashed are strings and integers.
value1 = 'coconut'
value2 = 1.23
hash = Sha1Hash(value1, value2)
Could always concat into a string, but feel like this is less than ideal:
hash = Sha1Hash( '%s%s' % (value1, value2))
Upvotes: 2
Views: 649
Reputation: 879729
It looks like you want a sha1 hash value. Python comes with a sha1 hash function, but it requires a string as input. Your data, (value1, value2)
, therefore needs to be serialized.
Since your data consists of only strings, ints and floats, you could serialize it and preserve the order of the values with
str([value1, value2])
import hashlib
value1 = 'coconut'
value2 = 1.23
m = hashlib.sha1()
m.update(str([value1, value2]))
print(m.hexdigest())
# 1381ae81c8a5b660cca5b8d4607aa378320e25e8
Upvotes: 1